Created
November 28, 2015 09:55
-
-
Save image72/98645bd12908131a8860 to your computer and use it in GitHub Desktop.
send file & callback
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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