且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Ruby on Rails中的send_data和send_file有什么区别?

更新时间:2023-11-24 11:33:46

send_data(_data_, options = {})
send_file(_path_, options = {}) 

此处的主要区别在于,您使用 send_data 传递DATA(二进制代码或其他代码),或使用 send_file 传递文件PATH.

Main difference here is that you pass DATA (binary code or whatever) with send_data or file PATH with send_file.

因此,您可以生成一些数据并将其作为内联文本或附件发送,而无需通过 send_data 在服务器上生成文件.或者,您可以使用 send_file

So you can generate some data and send it as an inline text or as an attachment without generating file on your server via send_data. Or you can send ready file with send_file

data = "Hello World!"
send_data( data, :filename => "my_file.txt" )

data = "Hello World!"
file = "my_file.txt"
File.open(file, "w"){ |f| f << data }
send_file( file )

出于性能考虑,***只生成一次文件,然后根据需要发送多次.因此send_file会更合适.

For perfomance it is better to generate file once and then send it as many times as you want. So send_file will fit better.

就流媒体而言,据我所知,这两种方法都使用相同的选项和设置,因此您可以使用X-Send或其他任何方法.

For streaming, as far as I understand, both of this methods use the same bunch of options and settings, so you can use X-Send or whatever.

UPD

发送数据并保存文件:

data = "Hello World!"
file = "my_file.txt"
File.open(file, "w"){ |f| f << data }
send_data( data )