Ruby on Rails 中的 send_data 和 send_file 有什么区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5535981/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the difference between send_data and send_file in Ruby on Rails?
提问by Mr. Black
Which one is best for streaming and file downloads?
哪一种最适合流式传输和文件下载?
Please provide examples.
请举例说明。
回答by fl00r
send_data(_data_, options = {})
send_file(_path_, options = {})
Main difference here is that you pass DATA (binary code or whatever) with send_dataor file PATH with send_file.
这里的主要区别在于您使用send_data传递 DATA (二进制代码或其他)或使用send_file传递文件 PATH 。
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
因此,您可以生成一些数据并将其作为内联文本或附件发送,而无需通过send_data在您的服务器上生成文件。或者您可以使用send_file发送准备好的文件
data = "Hello World!"
send_data( data, :filename => "my_file.txt" )
Or
或者
data = "Hello World!"
file = "my_file.txt"
File.open(file, "w"){ |f| f << data }
send_file( file )
For perfomance it is better to generate file once and then send it as many times as you want. So send_filewill fit better.
为了性能,最好生成一次文件,然后根据需要多次发送。所以send_file会更合身。
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.
对于流媒体,据我所知,这两种方法都使用相同的选项和设置,因此您可以使用 X-Send 或其他任何方法。
UPD
UPD
send_data and save file:
send_data 并保存文件:
data = "Hello World!"
file = "my_file.txt"
File.open(file, "w"){ |f| f << data }
send_data( data )

