To achieve this functionality, you will need to utilize the XHR FormData
API. This API was previously known as part of "XHR2" or "XHR Level 2", and is currently referred to as "XHR Advanced Features."
If you have the following HTML,
<input type="file" id="myFileField" name="myFile" />
You can upload it using the code snippet below:
var formData = new FormData();
formData.append("myFile", document.getElementById("myFileField").files[0]);
var xhr = new XMLHttpRequest();
xhr.open("POST", "myServletUrl");
xhr.send(formData);
The XHR will handle the appropriate headers, request body encoding, and the file will be available on the server side as a form-data
part with the name myFile
.
It's important to note that the FormData
API is not supported in older browsers. You can check browser compatibility on caniuse.com, where it shows implementation in Chrome 7+, Firefox 3.5+, Safari 5+, Internet Explorer 10+, and Opera 12+.
If you are using jQuery, avoid using the $.val()
function as it only returns the file name as a String
, which does not contain the file contents. Instead, use one of the alternatives provided.
...