krunal shah
krunal shah

Reputation: 16339

File upload with Rails?

I want to: click on button => select a file => click on "ok" (or double click the file) => upload to be launched automatically.

How can i achieve this with rails ?

Upvotes: 1

Views: 1633

Answers (3)

krunal shah
krunal shah

Reputation: 16339

Controller

  def file_upload
    begin
      ModelName.file_upload(params[:upload])
      flash[:notice] = "File has been uploaded successfully"
      redirect_to :action => "method_name"
    rescue Exception => e
      flash[:error] = "Error with upload! Please retry."
    end
  end

Model

 def self.file_upload(upload)
    name =  upload.original_filename
    directory = "#{DIR_PATH}"
    # create the file path
    path = File.join(directory, name)
    # write the file
    File.open(path, "wb") { |f| f.write(upload.read) }
  end

View

        <% form_tag({:controller => "controller_name", :action => "file_upload"}, {:multipart => true}) do%>
          <div class="fileinputs">
            <input type="file" name="upload" id="upload" class="file" onchange="this.form.submit();" />
            <div class="fakefile">
              <input class="upload_btn"/>
            </div>
          </div>
        <% end %>

CSS

div.fileinputs {
    position: relative;
}

div.fakefile {
    position: absolute;
    top: 0px;
    left: 0px;
    z-index: 1;
}

input.file {
    position: relative;
    text-align: right;
    -moz-opacity:0 ;
    filter:alpha(opacity: 0);
    opacity: 0;
    z-index: 2;
}

input.upload_btn {
    background:transparent url(/images/upload_btn.gif) no-repeat scroll 0px 0px ;
    width:79px;
    height:26px;
    cursor:pointer;
    border:0px;
}

input.upload_btn:hover {
    background:transparent url(/images/upload_btn.gif) no-repeat scroll 0px -40px ;
}

Upvotes: 6

DanS
DanS

Reputation: 18483

You can use paperclip as suggested, but I understand from your question you want to do away with a 'submit' button?

Have javascript listen for the onChange event on the file field and submit the form:

:onchange => "this.form.submit();"

Upvotes: 1

Nath
Nath

Reputation: 6864

Take a look at paperclip gem, Should cover everything assuming your using rails 3

https://github.com/thoughtbot/paperclip
http://www.jameswilding.net/blog/2010/07/paperclip-rails-3/

Upvotes: 1

Related Questions