Created
October 23, 2020 23:35
-
-
Save ChamsBouzaiene/6a4d9e9a6cca36f9745663129529c62e to your computer and use it in GitHub Desktop.
download file from link and upload it to remote server
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
// load status span | |
let Status = document.getElementById("status"); | |
// messages for status | |
const DOWN_START = "File is being downloaded ..."; | |
const DOWN_SUCCESS = "File is downloaded ..."; | |
const DOWN_FAIL = "File failed to download with : "; | |
const UPLOAD_START = "File is being Uploaded "; | |
const UPLOAD_SUCCESS = "File is Uploaded"; | |
const UPLOAD_FAILD = "File failed to upload with : "; | |
// function to update status span | |
const updateStatusMsg = (msg) => { | |
Status.innerHTML = msg; | |
}; | |
// instansiate XMLHttpRequest | |
let downloadReq = new XMLHttpRequest(); | |
let fileUrl = null; | |
// XMLHttpRequest Progress Listeners | |
downloadReq.addEventListener("progress", () => updateStatusMsg(DOWN_START)); | |
downloadReq.addEventListener("load", () => updateStatusMsg(DOWN_SUCCESS)); | |
downloadReq.addEventListener("error", () => updateStatusMsg(DOWN_FAIL)); | |
// Grab url from input | |
const getUrl = (self) => { | |
fileUrl = self.value; | |
}; | |
// Download File | |
const getFile = () => { | |
// [TIP] here i added a proxy for the app so you can have a valid cors so it can work locally | |
downloadReq.open( | |
"GET", | |
"https://api.allorigins.win/get?url=" + encodeURIComponent(fileUrl), | |
true | |
); | |
downloadReq.responseType = "blob"; | |
// Setup listener onLoad | |
downloadReq.onload = function () { | |
//When the file is downloaded we pass it to the upload function | |
uploadFile(downloadReq.response); | |
// if you want also to read the file and play it you can use this | |
let reader = new FileReader(); | |
reader.readAsDataURL(downloadReq.response); | |
reader.onload = function (e) { | |
console.log(reader); | |
console.log("DataURL:", e.target.result); | |
}; | |
}; | |
// Start Request | |
downloadReq.send(); | |
}; | |
// Upload | |
const uploadFile = (blob) => { | |
// Create A file | |
let audioFile = new File([blob], "audioFile"); | |
updateStatusMsg(UPLOAD_START); | |
// Sending Using fetch here you can add your node.js End point | |
fetch("http://www.example.net", { | |
method: "POST", | |
headers: { | |
"Content-Type": "Your Content Type", | |
}, | |
body: audioFile, | |
}) | |
.then((response) => response.json()) | |
.then((success) => updateStatusMsg(UPLOAD_SUCCESS)) | |
.catch((error) => updateStatusMsg(UPLOAD_FAILD + error.message)); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment