How to download file with Axios in node.js and write to the response
Asked Answered
M

1

1

I have the following video

URL: https://static.videezy.com/system/resources/previews/000/000/161/original/Volume2.mp4

and want to download it with Axios chunk by chunk and write to the response (send to client)

Here, I do not know how to use Range Header

const express = require('express')
const app = express()
const Axios = require('axios')


app.get('/download', (req, res) => {
    downloadFile(res)
})

async function downloadFile(res) {
    const url = 'https://static.videezy.com/system/resources/previews/000/000/161/original/Volume2.mp4'

    console.log('Connecting …')
    const { data, headers } = await Axios({
        url,
        method: 'GET',
        responseType: 'stream'
    })


    const totalLength = headers['content-length']
    let offset = 0

    res.set({
        "Content-Disposition": 'attachment; filename="filename.mp4"',
        "Content-Type": "application/octet-stream",
        "Content-Length": totalLength,
        // "Range": `bytes=${offset}` // my problem is here ....
    });

    data.on('data', (chunk) => {
        res.write(chunk)
    })

    data.on('close', function () {
        res.end('success')
    })

    data.on('error', function () {
        res.send('something went wrong ....')
    })
}


const PORT = process.env.PORT || 4000
app.listen(PORT, () => {
    console.log(`Server is running on port: ${PORT}`)
})
Messroom answered 12/4, 2021 at 20:59 Comment(0)
P
0

This is the way I use the range header. There is no need to do anything on the front end but in the backend you need to read them.

if (req.headers.range) {
    const range = req.headers.range;
    const positions = range.replace(/bytes=/, "").split("-");
    const start = parseInt(positions[0], 10);
    const total = file?.length;
    const end = positions[1] ? parseInt(positions[1], 10) : total - 1;
    const chunk = (end - start) + 1;

    stream = file.createReadStream({ start: start, end: end });
    stream.pipe(res);
    res.writeHead(206, {
        "Content-Range": "bytes " + start + "-" + end + "/" + total,
        "Accept-Ranges": "bytes",
        "Content-Length": chunk,
        "Content-Type": "video/mp4"
    });
} else {
    stream = file.createReadStream();
    stream.pipe(res);
}

In my case the variable file refers to the video file that I wish to stream to the customer.

Poundal answered 12/4, 2021 at 21:11 Comment(1)
thanks for your answer. could you please put your code in my snippet code to completeMessroom

© 2022 - 2024 — McMap. All rights reserved.