What is the difference between send_data and send_file in Ruby on Rails?

后端 未结 2 1453
后悔当初
后悔当初 2020-12-07 12:26

Which one is best for streaming and file downloads?

Please provide examples.

2条回答
  •  春和景丽
    2020-12-07 12:40

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

    Main difference here is that you pass DATA (binary code or whatever) with send_data or file PATH with 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" )
    

    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_file will fit better.

    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

    send_data and save file:

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

提交回复
热议问题