微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在 node.js 中使用 Axios 下载文件并写入响应

如何解决如何在 node.js 中使用 Axios 下载文件并写入响应

我有以下视频

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

并想用 Axios 一块一块地下载它并写入响应(发送到客户端)

这里不知道怎么用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}`)
})

解决方法

这是我使用范围标题的方式。前端不需要做任何事情,但在后端你需要阅读它们。

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);
}

在我的例子中,变量 file 是指我希望传输给客户的视频文件。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。