Cannot read file with send_file function in Rails 3

The code I'm using is:

In the view file:

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

In the controller:

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

I get an error message:

 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: double checked, the file exists. The same problem on the server, for all files (images, PDF files, videos) in all relevant controllers.

+6
source share
4 answers

The problem was:

I used

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

It should be

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

PS: Make sure you confirm that the image / recording exists.

+15
source

Just change the URL method along the path:

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

I don’t know how you save the attachment URL of the image, but in general, the file name should look like this:

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

Please note that in the end there is no "? Xxxxx".

You can check your file system whether the file name is "Screen Shot 2011-11-04 at 3.14.03 PM.png" or "Screen Shot 2011-11-04 at 3.14.03 PM.png? 1320582022".

For the url file, it could be something like: http://example.com/xxx?dddd , what is the "?" separate the path and options. The string "dddd" is a parameter when requesting a URL; it is not part of the path or file name. Parameters only support URLs, not the local file name.

So, I think you need to check the save code for the attachment URL of the image, which should exclude options and only the file name. And make sure the name is exactly the same as the file saved on disk.

And you can try to open the file, although irb directly, and check the output:

 >>> 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') 

Others, try finding the location of the error in the send_file file and check the file name.

I still can not understand what the problem is, just some suggestion.

+1
source

Does this ?1320582022 file name? I'm not sure about the white spaces in the file name, maybe they need to slip away.

0
source

Source: https://habr.com/ru/post/903068/


All Articles