Created
June 14, 2020 01:57
-
-
Save geeksilva97/f1d3bf9884b040afabf72f1bcc7b1ae2 to your computer and use it in GitHub Desktop.
Upload with Vanilla JS
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 _(el) { | |
return document.getElementById(el); | |
} | |
function uploadFile() { | |
var file = _("file1").files[0]; | |
// alert(file.name+" | "+file.size+" | "+file.type); | |
var formdata = new FormData(); | |
formdata.append("file", file, "video.mov"); | |
var ajax = new XMLHttpRequest(); | |
ajax.upload.addEventListener("progress", progressHandler, false); | |
ajax.addEventListener("load", completeHandler, false); | |
ajax.addEventListener("error", errorHandler, false); | |
ajax.addEventListener("abort", abortHandler, false); | |
ajax.open("POST", "http://localhost:5000/profile/upload"); // http://www.developphp.com/video/JavaScript/File-Upload-Progress-Bar-Meter-Tutorial-Ajax-PHP | |
//use file_upload_parser.php from above url | |
ajax.send(formdata); | |
} | |
function progressHandler(event) { | |
_("loaded_n_total").innerHTML = "Uploaded " + event.loaded + " bytes of " + event.total; | |
var percent = Math.round((event.loaded / event.total) * 100); | |
_("progressBar").value = percent; | |
_("status").innerHTML = percent + "% uploaded... please wait"; | |
} | |
function completeHandler(event) { | |
_("status").innerHTML = event.target.responseText; | |
_("progressBar").value = 0; //wil clear progress bar after successful upload | |
} | |
function errorHandler(event) { | |
_("status").innerHTML = "Upload Failed"; | |
} | |
function abortHandler(event) { | |
_("status").innerHTML = "Upload Aborted"; | |
} | |
_('upload_form').addEventListener('submit', (e) => { | |
e.preventDefault(); | |
uploadFile(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment