如何在 node.js 中使用 Axios 下载文件并写入响应 [英] How to download file with Axios in node.js and write to the response

查看:38
本文介绍了如何在 node.js 中使用 Axios 下载文件并写入响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下视频

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

并希望使用 Axios 逐块下载并写入响应(发送到客户端)

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

这里,我不知道如何使用Range Header

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

推荐答案

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

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

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

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

这篇关于如何在 node.js 中使用 Axios 下载文件并写入响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆