如何在rails中上传文件 [英] how to upload files in rails

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

问题描述

我的应用程序是一个surveybuilder ...它需要上传用户的CVS文件,我工作与铁轨3.1.3。,红宝石1.9.2和设计1.5.3进行身份验证,但我试过: http:// www。 jedi.be/blog/2009/04/10/rails-and-large-large-file-uploads-looking-at-the-alternatives/ ,但不适合我...任何人都可以告诉我如何(一步一步...是的,我是一个begginer)在轨道上传CVS文件3.1.3?如果你的目标是上传一个文件到一个目录,你不应该使用Carrierwave或Paperclip 。这些宝石有很多图像处理和额外的选项的支持。

我建议你看看Ruby文件类和打开方法更具体。 http://www.ruby-doc.org /core-1.9.3/File.html#method-c-open



类似下面的内容应该可以做到这一点:

 #public / csv是您要保存文件的目录
#upload [datafile]是填充的数据文件输入标签在你的html格式
path = File.join(public / csv,upload [datafile]。original_filename)
File.open(path,wb){| f |请记住,你的公共目录下面是一个公共目录世界是可以访问的。如果您需要将这些文件保存在更私密的位置,请确保您的应用程序只能读取和写入目录。



另外,如果您使用的是CSV文件,请务必阅读Ruby CSV类: http:/ / /ruby-doc.org/stdlib-1.9.2/libdoc/csv/rdoc/CSV.html 。它使得使用CSV文件变得轻而易举。


My app is a surveybuilder...it needs upload cvs files by users, Im working with rails 3.1.3., ruby 1.9.2 ande devise 1.5.3 for authentication, but I tried: http://www.jedi.be/blog/2009/04/10/rails-and-large-large-file-uploads-looking-at-the-alternatives/ but don't works for me...can anybody tell me how to (step by step...yes I'm a begginer) upload cvs files in rails 3.1.3??? thanks in advance.

解决方案

If your goal is to upload a file to a directory you shouldn't have to use Carrierwave or Paperclip. Those gems have a lot of support for image processing and extra options.

I suggest you look at the Ruby file class and the open method to be more specific. http://www.ruby-doc.org/core-1.9.3/File.html#method-c-open

Something like the following should do the trick:

# "public/csv" is the directory you want to save the files in
# upload["datafile"] is the data populated by the file input tag in your html form 
path = File.join("public/csv", upload["datafile"].original_filename)
File.open(path, "wb") { |f| f.write(upload["datafile"].read) }

Keep in mind, your public directory is accessible to the world. If you need to save these in a more private location, make sure the directory is only readable and writable by your app.

Also, if you are working with CSV files, be sure to read through the Ruby CSV class: http://ruby-doc.org/stdlib-1.9.2/libdoc/csv/rdoc/CSV.html. It makes working with CSV files a breeze.

这篇关于如何在rails中上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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