Created
April 25, 2022 18:45
-
-
Save cullophid/2f1b9928879c5ead777a28a01baaace4 to your computer and use it in GitHub Desktop.
Download file
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
const downloadFile = async () => { | |
setDownLoading(true); | |
setProgress(0); | |
let content; | |
if (files && files.length > 0) { | |
content = JSON.stringify({ | |
"package-name": props.filename ?? "download-bundle.zip", | |
"error-log-name": "errors.txt", | |
groups: [ | |
{ | |
items: | |
files.length > 0 | |
? files.map(files => ({ | |
source: { | |
url: files.url, | |
}, | |
target: { | |
name: files.name, | |
}, | |
})) | |
: [], | |
}, | |
], | |
}); | |
} | |
if (body) { | |
content = JSON.stringify(body()); | |
} | |
if (stringifiedBody) { | |
content = stringifiedBody; | |
} | |
// download the files using XMLHTTPRequest (so we get progress updates) | |
const request = new XMLHttpRequest(); | |
request.open("POST", PACKAGING_SERVICE_URL, true); | |
Object.entries( | |
props.headers ?? { | |
"content-type": "application/json", | |
...getAuthHeaders(), | |
}, | |
).forEach(([header, value]) => { | |
request.setRequestHeader(header, value); | |
}); | |
request.responseType = "blob"; | |
request.addEventListener("progress", e => setProgress(e.loaded)); | |
request.onload = function () { | |
setDownLoading(false); | |
// Only handle status code 200 | |
if (request.status === 200) { | |
let filename = props.filename; | |
if (typeof filename !== "string") { | |
// Try to find out the filename from the content disposition `filename` value | |
const disposition = request.getResponseHeader("content-disposition"); | |
const matches = | |
typeof disposition === "string" | |
? /"([^"]*)"/.exec(disposition) | |
: null; | |
filename = | |
matches !== null && typeof matches[1] === "string" | |
? matches[1] | |
: "bundle.zip"; | |
} | |
// The actual download from the browser to disk | |
const blob = new Blob([request.response], { type: "application/zip" }); | |
const link = document.createElement("a"); | |
link.href = window.URL.createObjectURL(blob); | |
link.download = filename; | |
document.body.appendChild(link); | |
link.click(); | |
document.body.removeChild(link); | |
props.onCompleted?.(); | |
} | |
}; | |
request.addEventListener("error", e => { | |
setDownLoading(false); | |
props.onError?.(e); | |
}); | |
request.send(content); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment