2011-12-05 17 views
6

的代碼我使用:無法讀取與由send_file功能文件中的Rails 3

鑑於文件:

<%= link_to "Download", download_image_path(image) %> 

在控制器:

def download 
    @image = Image.find(params[:id]) 
    send_file "#{RAILS_ROOT}/public" + @image.attachment.url 
end 

我得到一個錯誤:

Cannot read file /Users/mohit/projects/my_app/public/system/attachments/4/original/Screen Shot 2011-11-04 at 3.14.03 PM.png?1320582022 

PS:重複檢查,文件存在。服務器上的所有相關控制器中的所有文件(圖像,pdf,視頻)都是同樣的問題。

回答

15

問題是:

我用

@image = Image.find(params[:id]) 
send_file "#{RAILS_ROOT}/public" + @image.attachment.url 

應該

@image = Image.find(params[:id]) 
send_file @image.attachment.path 

PS:請確保您驗證圖像/記錄存在。

+0

如果使用brakeman分析代碼,那麼它會將錯誤顯示爲用作文件名的MOdel屬性。只是跑剎車。 其考慮爲 send_file Image.find(params [:id])。uploaded_file.path – errakeshpd

0

這個?1320582022屬於文件名嗎?我不確定文件名中是否有空白,也許他們需要轉義。

+0

屏幕截圖2011-11-04在03年3月14日PM.png是文件名和1320582022即將原因即時得到問題的發展模式.. –

1

我不知道你是怎麼保存的圖片附件的URL,但在一般情況下,文件名應該想:

/Users/mohit/projects/my_app/public/system/attachments/4/original/Screen Shot 2011-11-04 at 3.14.03 PM.png 

注意它不到底有「XXXXX?」。

你可以檢查你的文件系統,文件名是「Screen Shot 2011-11-04 at 3.14.03 PM.png」還是「Screen Shot 2011-11-04 at 3.14.03 PM.png?1320582022 」。

對於文件url,它可能類似於:http://example.com/xxx?dddd,其中字符「?」拆分路徑和參數。字符串「dddd」是請求url路徑時的參數,它不是路徑或文件名的一部分。參數只支持url,不支持本地文件名。

所以,我認爲你需要檢查保存圖像附件url的代碼,它需要排除參數和唯一的文件名。並確保名稱與保存到磁盤的文件完全相同。

而且你可以嘗試直接打開該文件雖然IRB並檢查輸出:

>>> irb 
irb> f = open('/Users/mohit/projects/my_app/public/system/attachments/4/original/Screen Shot 2011-11-04 at 3.14.03 PM.png?1320582022') 

其他人,試圖找到在由send_file錯誤位置,並檢查文件名。

我仍然無法確定問題究竟是什麼,只是一些建議。

+0

這是個好建議.. –

2

由路徑只需更改URL方法:

send_file @image.attachment.path # this is the right way!.