how to upload files in rails

前端 未结 3 1728
逝去的感伤
逝去的感伤 2021-01-07 13:34

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.

3条回答
  •  悲哀的现实
    2021-01-07 14:09

    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.

提交回复
热议问题