Let's say I have this element on the page:
<input id="image-file" type="file" />
This will create a button that allows the users of the web page to select a file via an OS "File open..." dialog in the browser.
Let's say the user clicks said button, selects a file in the dialog, then clicks the "Ok" button to close the dialog.
The selected file name is now stored in:
document.getElementById("image-file").value
Now, let's say that the server handles multi-part POSTs at the URL "/upload/image".
How do I send the file to "/upload/image"?
Also, how do I listen for notification that the file is finished uploading?
Unless you're trying to upload the file using ajax, just submit the form to
/upload/image
.If you do want to upload the image in the background (e.g. without submitting the whole form), you can use ajax:
As its creator I'm biased ;) but you could also consider using something like https://uppy.io. It does file uploading without navigating away from the page and offers a few bonuses like drag & drop, resuming uploads in case of browser crashes/flaky networks, and importing from e.g. Instagram. It's also open source and does not rely on jQuery or anything like that.
If you are in fact seeking a pure javascript way to upload an image, then the following tutorial from 2009 will tell you exactly how to do that:
http://igstan.ro/posts/2009-01-11-ajax-file-upload-with-pure-javascript.html
I ran into this when I wanted to add basic-authentication to a form submission, without enabling cookies. E.g. when you have username/password fields with your filename, file, etc fields.
Hope this helps!
PURE JS
Use following code:
xhr.setRequestHeader('Content-Type', 'multipart/form-data');
- this will be set automatically by browser./upload/image
you can use full address likehttp://.../upload/image
.let user = {name:'john', age:34}
in this way:formData.append("user", JSON.stringify(user));
Editable example here. More info about response/error handling here.