Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4: How to upload files with AJAX

Tags:

I want to upload files with AJAX. In the past I accomplished this by using the magical jQuery form plugin and it worked great. Currently I'm building a Rails app and trying to do things "The Rails Way" so I'm using the Form Helper and the paperclip gem to add file attachments.

The rails docs warn that the Form Helper does not work for AJAX file uploads:

Unlike other forms making an asynchronous file upload form is not as simple as providing form_for with remote: true. With an Ajax form the serialization is done by JavaScript running inside the browser and since JavaScript cannot read files from your hard drive the file cannot be uploaded. The most common workaround is to use an invisible iframe that serves as the target for the form submission.

It seems clear there's no off-the-shelf solution. So I'm wondering what's the smartest thing to do. Seems like I have several options:

  1. Use the form helper and the iframe trick.
  2. Use the form helper + load jQuery form plugin to submit the file (not sure if this will play nice with Rails's authenticity token, etc)
  3. Use the form helper + paperclip + [some other gem] to extend it's functionality to allow AJAX form submission.

All three seem possible. I know the least about #3, specifically the [some other gem] part. I found two similar questions (this and this) which mention a branch of Pic-Upload called Uploadify but those are both 2 years old and deal with Rails 2 and 3 (and Uploadify hasn't been updated in years). So given how much has changed, I think this is really a whole new question:

What's the best way to upload files with AJAX in Rails 4?

like image 363
emersonthis Avatar asked Sep 03 '13 14:09

emersonthis


People also ask

Can we upload file using AJAX?

File upload is not possible through AJAX. You can upload file, without refreshing page by using IFrame .

How to send file object using AJAX?

A JavaScript method must be coded to initiate the asynchronous Ajax based file upload; A component must exist on the server to handle the file upload and save the resource locally; The server must send a response to the browser indicating the JavaScript file upload was successful; and.

How do I add AJAX in Rails?

In Rails, submitting an AJAX request can be done as easily as adding remote: true to a link, button, or form. From there you can have any response be some JavaScript code waiting on the server side, and it will execute in the client's browser. Here's the simplest code example of UJS via AJAX in a link.


1 Answers

Have a look into the remotipart gem: https://github.com/JangoSteve/remotipart -- may get you all of the way there with very little work!

like image 198
pdobb Avatar answered Nov 27 '22 01:11

pdobb