繁体   English   中英

如何在 node.js 中下载带有 Axios 的文件并写入响应

[英]How to download file with Axios in node.js and write to the response

我有以下视频

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

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

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

在我的情况下,变量文件是指我希望 stream 给客户的视频文件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM