2013-03-14 57 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,如果所有的歌曲存在,發送郵件作爲臨時文件工作得很好。