'How to download large files from a server from frontend (VueJS) using fetch or axios. Achieve simultaneous download while fetching
My frontend (written in VueJS) needs to download a large file from a server (~1GB but can get even larger). My current approach is using streamSaver however, although this seems to work fine when I download files while testing locally, it seems to struggle when testing it on other devices (android phone while pointing the server to 0.0.0.0)
Front end Code for downloading, I'm currently piping the fetch data to streamSaver, however from what I understand, the fetch request has to complete before the download action starts, which isn't really the solution I require. I want to be able to start the download simultaneously.
const fileStream = streamSaver.createWriteStream(fileName);
const res = await fetch("gets/download-file?" + new URLSearchParams({
relPath: path.join(forPath, fileName)
}))
const readableStream = res.body
if (window.WritableStream && readableStream.pipeTo) {
return readableStream.pipeTo(fileStream)
.then(() => console.log('done writing'))
}
window.writer = fileStream.getWriter()
const reader = res.body.getReader()
const pump = () => reader.read()
.then(res => res.done
? window.writer.close()
: window.writer.write(res.value).then(pump))
pump()
My server is written in express.js, and I have also tried streaming the data from the server side as well
router.get("/download-file", checkPath, async (req, res) => {
try {
const relativePath = req.query.relPath;
const fullPath = path.join(UPLOAD_FOLDER, relativePath);
console.log(green("Downloading: ", fullPath))
// res.sendFile(fullPath, (err) => {
// if (err) console.log(red(err))
// })
res.setHeader('Content-Type', 'application/octet-stream');
fs.createReadStream(fullPath).pipe(res);
} catch (err) {
console.log(red(err))
}
})
I have seen Stream large blob file using StreamSaver.js, and other similar answers but they all seem to have similar flaws of having to complete the fetch request and wait till then before streaming a download, which isn't what I'm looking for.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
