vvekselva
vvekselva

Reputation: 823

Asynchronous JQUERY File Upload

I have HTML form with a file input type. I need to submit the form asynchronously to the server. The server listens for a incoming file upload (multi part file upload) request. Is it possible to achieve this using jquery.

Upvotes: 0

Views: 9362

Answers (3)

404
404

Reputation: 1372

You can easily use jQuery's $.ajax() method to send files if FormData and the File API are supported (both HTML5 features).

You can also send files without FormData but either way the File API must be present to process files in such a way that they can be sent with XMLHttpRequest (Ajax).

$.ajax({
  url: 'file/destination.html', 
  type: 'POST',
  data: new FormData($('#formWithFiles')[0]),  // The form with the file inputs.
  processData: false  // Using FormData, don't process data.
}).done(function(){
  console.log("Success: Files sent!");
}).fail(function(){
  console.log("An error occurred, the files couldn't be sent!");
});

For a quick, pure JavaScript example see "Sending files using a FormData object".

If you want to add a fallback for older browsers or if you want just one cross-browser implementation use the Bifröst. It adds an extra jQuery Ajax transport allowing to send files with plane old $.ajax().

Simply add jquery.bifrost.js and make the request:

$.ajax({
  url: 'file/destination.html', 
  type: 'POST',
  // Set the transport to use (iframe means to use Bifröst)
  // and the expected data type (json in this case).
  dataType: 'iframe json',                                
  fileInputs: $('input[type="file"]'),  // The file inputs containing the files to send.
  data: { msg: 'Some extra data you might need.'}
}).done(function(){
  console.log("Success: Files sent!");
}).fail(function(){
  console.log("An error occurred, the files couldn't be sent!");
});

Good luck!

Upvotes: 2

Trufa
Trufa

Reputation: 40717

I would take a look at this jQuery plugin:

http://malsup.com/jquery/form/#file-upload

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038800

Is it possible to achieve this using jquery.

No, not directly with jQuery.

You could use the HTML5 File API: https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications

Or if you need to support legacy browsers you could use some plugin such as Uploadify, Fine Uploader or the jQuery form plugin.

Upvotes: 1

Related Questions