Skip to content

Instantly share code, notes, and snippets.

@image72
Created November 28, 2015 09:55
Show Gist options
  • Save image72/98645bd12908131a8860 to your computer and use it in GitHub Desktop.
Save image72/98645bd12908131a8860 to your computer and use it in GitHub Desktop.
send file & callback
function sendFile(option, cb) {
/* {
field: name,
url: '/path/to/upload',
file: FileObject
} */
var field = option.field;
var xhr = new XMLHttpRequest();
var fd = new FormData();
var resp;
xhr.open("POST", option.url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
// Handle response.
resp = JSON.parse(xhr.responseText);
cb && cb(resp);
}
};
xhr.addEventListener('load', function () {
resp = JSON.parse(xhr.responseText);
//cb(resp);
}, false);
// send multiple files;
//var files = Array.apply(null,option.file);
//files.forEach(function(item) {
// fd.append(field, item, item.name);
//})
fd.append(field, option.file);
// Initiate a multipart/form-data upload
xhr.send(fd);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment