The best way in browsers that support it, is to send the file as a Blob, or using FormData if you want a multipart form. You do not need a FileReader for that. This is both simpler and more efficient than trying to read the data.
If you specifically want to send it as multipart/form-data
, you can use a FormData object:
var xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.open("POST", '/pushfile', true);
var formData = new FormData();
// This should automatically set the file name and type.
formData.append("file", file);
// Sending FormData automatically sets the Content-Type header to multipart/form-data
xmlHttpRequest.send(formData);
You can also send the data directly, instead of using multipart/form-data
. See the documentation. Of course, this will need a server-side change as well.
// file is an instance of File, e.g. from a file input.
var xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.open("POST", '/pushfile', true);
xmlHttpRequest.setRequestHeader("Content-Type", file.type);
// Send the binary data.
// Since a File is a Blob, we can send it directly.
xmlHttpRequest.send(file);
For browser support, see: http://caniuse.com/#feat=xhr2 (most browsers, including IE 10+).