Created
January 10, 2014 14:42
-
-
Save nickrussler/8355398 to your computer and use it in GitHub Desktop.
Upload file with jquery and formdata (untested, should work)
This file contains hidden or 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
/** | |
* Shows Filepicker dialog and uploads the chosen file to the given url | |
* | |
* @param url URL where the file is sent | |
* @param successHandler Success callback function | |
* @param errorHandler Error callback function | |
* @see https://developer.mozilla.org/en-US/docs/Web/API/FormData | |
*/ | |
function uploadFile(url, successHandler, progressHandler, errorHandler) { | |
var $fileInput = $('<input type=file>'); | |
$fileInput.change(function(){ | |
var fd = new FormData(); | |
var file = this.files[0]; | |
fd.append('file', file); | |
$.ajax({ | |
url: url, | |
type: "POST", | |
data: fd, | |
processData: false, | |
contentType: false, | |
success: function(response) { | |
successHandler(response); | |
}, | |
error: function(jqXHR, textStatus, errorMessage) { | |
errorHandler(jqXHR, textStatus, errorMessage); | |
}, | |
xhr: function() { | |
var req = new window.XMLHttpRequest(); | |
req.upload.addEventListener("progress", function(e) { | |
progressHandler(e); | |
if(e.lengthComputable) { | |
progressHandler(((100*e.loaded/e.total).toPrecision(3))); | |
} | |
}, false); | |
return req; | |
} | |
}); | |
}); | |
$fileInput.click(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment