2013-03-14 56 views
4

我试图用一个临时文件西纳特拉的内置send_file命令,但它似乎并没有对临时文件的工作。由send_file在西纳特拉

我基本上做到以下拉上的MP3音乐专辑:

get '/example' do 
    songs = ... 
    file_name = "zip_test.zip" 
    t = Tempfile.new(['temp_zip', '.zip']) 
    # t = File.new("testfile.zip", "w") 
    Zip::ZipOutputStream.open(t.path) do |z| 
    songs.each do |song| 
     name = song.name 
     name += ".mp3" unless name.end_with?(".mp3") 
     z.put_next_entry(name) 
     z.print(open(song.url) {|f| f.read }) 
     p song.name + ' added to file' 
    end 
    end 
    p t.path 
    p t.size 

    send_file t.path, :type => 'application/zip', 
         :disposition => 'attachment', 
         :filename => file_name, 
          :stream => false 
    t.close 
    t.unlink 
end 

当我使用t = File.new(...)事情按预期工作,但我不希望使用File,因为这将有并发问题。

当我使用t = Tempfile.new(...),我得到:

!! Unexpected error while processing request: The file identified by body.to_path does not exist` 

编辑:它看起来像的部分问题是,我传送给多个文件。如果我只发送一首歌曲,Tempfile系统也可以工作。

+2

如果你使用一个预先构建的zip文件,而其中有多个文件,而不是使用'Zip :: ZipOutputStream.open',会发生什么?...?此外,[由send_file发送停止(https://github.com/sinatra/sinatra/blob/v1.3.5/lib/sinatra/base.rb#L308),所以't.close'和't.unlink'是不需要的(无论如何,文件系统应该照顾到这一点)。 – iain 2013-03-15 21:20:24

回答

0

我的猜测是,你有你的歌曲名称中的一个错字,或者也许在song.url的最后部分的一个斜线?我adopted your code,如果所有的歌曲存在,发送邮件作为临时文件工作得很好。