smark
smark

Reputation: 255

Rails 3 - upload files to public directory

I'm looking for a simple way to upload a file (an xml file) to the public directory of Rails 3. Once it's there I want to open it, parse the contents and delete the file after that.

Whenever I searched for file upload I encountered Paperclip. But I don't want to associate the file with an object. I just want to upload it. What's the easiest way to do this?

Upvotes: 22

Views: 22723

Answers (3)

fl00r
fl00r

Reputation: 83680

a. Form

<%= form_for :file_upload, :html => {:multipart => true} do |f| %>
  <%= f.file_field :my_file %>
  <%= f.submit "Upload" %>
<% end %>

b. controller

def file_upload  
  require 'fileutils'
  tmp = params[:file_upload][:my_file].tempfile
  file = File.join("public", params[:file_upload][:my_file].original_filename)
  FileUtils.cp tmp.path, file
  ... # YOUR PARSING JOB
  FileUtils.rm file
end

But you can parse just tempfile, so you don't need to copy it to public dir and it will automatically deleted

Upvotes: 45

Mikaele
Mikaele

Reputation: 85

img = params[:user][:photo]
File.open(Rails.root.join('public','uploads',img.original_filename),'wb') do |file| file.write(img.read)

Upvotes: -1

Leonid
Leonid

Reputation: 179

I received an error indicating "undefined method `cp' for File:Class". Realized that this should actually be updated as follows:

Right code for file_uplad method:

def file_upload
    tmp = params[:file_upload][:my_file].tempfile
    require 'ftools'
    file = File.join("public", params[:file_upload][:my_file].original_filename)
    FileUtils.cp tmp.path, file
end

Upvotes: 3

Related Questions