簡體   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