如何在rails 3.1.1中将图像写入文件系统? [英] How to write an image to filesystem in rails 3.1.1?

查看:37
本文介绍了如何在rails 3.1.1中将图像写入文件系统?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我觉得我应该非常接近,但我无法让它完全正确地工作.

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

我正在使用文件传输将图像从我的 phonegap 应用程序发送到我的 rails 应用程序(3.1.1 ruby​​ 1.8.7 btw).

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.

这是参数哈希:

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">}

基本上,我可以通过 params[:file] 访问文件.现在我只需要将该图像写入我的文件系统.我没有图像对应的模型,所以我真的不需要回形针.现在,我能想到的最好的方法是:

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

这是我得到的错误:

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

所以,这很奇怪.我可以让这些命令在我的 irb 中工作:

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

但是,这不起作用:

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

我收到此错误:类型错误(无法将 ActionDispatch::Http::UploadedFile 转换为 String):

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

我在 irb 中使用 ruby​​ 1.9.3,但这些命令应该是相同的...

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

所以我现在很难过.

推荐答案

代码应该是:

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

File.open("ihatedetails.jpg",'wb') { |f|f.write params[:file].read } 一行.

这篇关于如何在rails 3.1.1中将图像写入文件系统?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆