How to write an image to filesystem in rails 3.1.1?

落花浮王杯 提交于 2019-12-23 01:45:16

问题


I feel like I should be really close, but I can't get this to work just quite right.

I'm sending an image using filetransfer from my phonegap app to my rails app (3.1.1 ruby 1.8.7 btw).

I want to write the file to the filesystem.

This is the params hash:

Parameters: {"file"=>#<ActionDispatch::Http::UploadedFile:0x7f1e2baa94e8 @tempfile=#<File:/tmp/RackMultipart20120607-5707-owzii5-0>, 
@headers="Content-Disposition: form-data; name=\"file\"; filename=\"image.jpg\"\r\nContent-Type: image/jpeg\r\n", 
@content_type="image/jpeg", @original_filename="image.jpg">}

Basically, I can access the file through params[:file]. Now I need to just write that image on to my filesystem. I don't have a model for the image to correspond to, so I don't really need paperclip. Right now, the best I could come up with is this:

open(params[:file]) do |image|
  File.open("theiamge.jpg","wb"){|file| file.puts image.read }
end

This is the error I get:

TypeError (can't convert ActionDispatch::Http::UploadedFile into String):

EDIT:

So, this is rather odd. I can get these commands working in my irb:

 File.open('newimage.jpg', 'wb') do |f|
   f.write File.open('oldimage.jpg').read
 end

However, this doesn't work:

 File.open("ihatedetails.jpg",'wb') do |f|
   f.write File.open(params[:file]).read
 end

I get this error: TypeError (can't convert ActionDispatch::Http::UploadedFile into String):

I'm using ruby 1.9.3 in my irb, but these commands should be the same...

So I'm stumped right now.


回答1:


The code should be:

File.open("ihatedetails.jpg",'wb') do |f|
  f.write params[:file].read
end

or File.open("ihatedetails.jpg",'wb') { |f| f.write params[:file].read } in one line.



来源:https://stackoverflow.com/questions/10942930/how-to-write-an-image-to-filesystem-in-rails-3-1-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!