1

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.

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

7 Comments

do you mean I can just do var file = document.querySelector('input[type="file"]').files[0]; xhr.send(file)?
developer.mozilla.org/en-US/docs/Web/API/… it's not supported by IE and Safari? I have a feeling this chart is out of date.
what's the best way to feature check this? is modernizr's file-api check sufficient?
developer.mozilla.org/en-US/docs/Web/API/… file api is only supported by chrome?
File API is supported on all browsers other than IE 9 and older, for the most part.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.