【问题标题】:How to download file with Axios in node.js and write to the response如何在 node.js 中使用 Axios 下载文件并写入响应
【发布时间】:2021-07-07 23:04:04
【问题描述】:

我有以下视频

网址: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}`)
})

【问题讨论】:

    标签: javascript node.js axios chunking


    【解决方案1】:

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

    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 指的是我希望流式传输给客户的视频文件。

    【讨论】:

    • 感谢您的回答。你能把你的代码放在我的sn-p代码中完成吗
    猜你喜欢
    • 1970-01-01
    • 2017-06-15
    • 2019-08-17
    • 1970-01-01
    • 2012-06-26
    • 2019-01-02
    • 2013-01-16
    • 2021-09-22
    • 1970-01-01
    相关资源
    最近更新 更多