如何在rails中上传文件 [英] how to upload files in rails
问题描述
我建议你看看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屋!