Jonathan Ong
Jonathan Ong

Reputation: 20315

How can I upload a file using AJAX without using multipart?

The only file my app allows users to upload are images, and they are always uploaded as the sole input field in a form. Thus, multipart is unnecessary, and I could much more easily consume the file without a multipart parser.

How can upload a file without using multipart using AJAX and vanilla Javascript? Also, it should generally support the latest version of all browsers.

Upvotes: 1

Views: 1599

Answers (1)

Ray Nicholus
Ray Nicholus

Reputation: 19890

You can simply send the associated File or Blob itself via XHR level 2. For example, in the upload library I maintain (Fine Uploader) you can elect to have files sent in multipart encoded POST requests (all browsers) or non MPE requests (only browsers that support the File API).

To send the file in a MPE POST request, as you may already know, you must either add your file to a FormData object and send that via XHR2, or submit a form containing a file input. If you want to upload a file in a non MPE POST request, simply do this:

xhr.send(file);

Of course, this can only be done in browsers that support the File API. Also, if you want to send any parameters along with your file, you will have to include them in the query string.

Upvotes: 4

Related Questions