简体   繁体   English

如何在Rails中上传文件

[英]how to upload files in rails

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??? 我的应用程序是SurveyBuilder ...它需要由用户上传cvs文件,我正在使用rails 3.1.3。,ruby 1.9.2并设计了1.5.3进行身份验证,但是我尝试了: http : //www.jedi.be / blog / 2009/04/10 / rails-and-large-large-file-uploads-look-at-the-alternatives /,但不适用于我...有人可以告诉我如何操作(逐步操作)。 ..是的,我是一个初学者)在Rails 3.1.3中上传cvs文件??? thanks in advance. 提前致谢。

If your goal is to upload a file to a directory you shouldn't have to use Carrierwave or Paperclip. 如果您的目标是将文件上传到目录,则不必使用Carrierwave或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. 我建议您仔细看一下Ruby文件类和open方法。 http://www.ruby-doc.org/core-1.9.3/File.html#method-c-open 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 . 另外,如果您使用的是CSV文件,请务必通读Ruby CSV类: http : //ruby-doc.org/stdlib-1.9.2/libdoc/csv/rdoc/CSV.html It makes working with CSV files a breeze. 它使处理CSV文件变得轻而易举。

Carrierwave ( https://github.com/jnicklas/carrierwave ) is pretty much the standard when it comes to files uploading. Carrierwave( https://github.com/jnicklas/carrierwave )在文件上传方面几乎是标准。

Otherwise, here is a simplier method if you don't need a full-fledged gem: Rails 3 - upload files to public directory 否则,如果您不需要完整的gem,这是一个更简单的方法: Rails 3-将文件上传到公共目录

我在github中使用javascript在Rails 3.2.1中找到了一个出色的项目,您可以上传文件并将其保存在数据库中,是通过sqlite完成的,但是将其更改为mysql很容易,这里是链接: 在Rails 3.2.1,javascript和sqlite

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM