【问题标题】:Download file from a request made to another server without saving it on the server从向另一台服务器发出的请求下载文件而不将其保存在服务器上
【发布时间】:2021-10-03 20:30:46
【问题描述】:

我正在向另一台服务器发出请求以下载 zip 文件,我现在所做的是向另一台服务器发出请求,该服务器以 zip 文件响应,我将其保存在我所在的服务器上并使用 res 发送。下载, 我想要的是能够下载该 zip 而不必将其保存在本地存储中

const form = new FormData();
    form.append("Content-Type", "application/json");
    form.append("instancia", req.file.buffer, req.file.originalname);
    form.append("parametros", "XYZ);


    const response = await axios.post("http://localhost:8080/archivos", form, {
        headers: {
            ...form.getHeaders(),
        },
        responseType: "stream",
    });
    
    let headerLine = response.data.headers["content-disposition"];
    let startFileNameIndex = headerLine.indexOf('"') + 1;
    let endFileNameIndex = headerLine.lastIndexOf('"');
    let filename = headerLine.substring(startFileNameIndex, endFileNameIndex);
      
    response.data.pipe(FS.createWriteStream(__dirname + "/" + filename).on('close',function(){
        res.setHeader('Content-Disposition', filename);
        res.download(__dirname + "/" + filename);
        
      }))

这真的可能吗?

【问题讨论】:

  • 我不确定这是否是您要问的,但您当然可以将一个流通过管道传输到另一个流中,到达的位会立即发送出去并且永远不会在本地存储(除了暂时存储的小块在内存中)。
  • 你知道我在哪里可以看到如何做到这一点吗?我是新手:(

标签: javascript node.js axios microservices multer


【解决方案1】:

您可以将一个流传输到另一个流,到达的位会立即发送到另一个流,而无需将整个文件累积到本地存储中。下面是 Express 中的 GET 请求示例,该请求从外部服务器获取内容并通过管道将其返回到 Express 响应,并将其格式化为浏览器承诺用户下载的附件。您显然可以根据需要设置 content-xxx 标头。这里我已经配置好了,所以浏览器会提示用户保存文件。

const express = require('express');
const https = require('https');
const app = express();

app.get("/file", (req, res) => {
    const request = https.get("https://www.google.com", readable => {
        const contentType = readable.headers['content-type'];
        res.set({
            'Content-Type': contentType,
            'Content-Disposition': 'attachment; filename="google.html"',
        });
        readable.pipe(res);
    }).on('error', e => {
        console.log(e);
        if (res.headersSent) {
            // if headers already sent, not much we can do on an error,
            // but just end the connection
            res.end();
        } else {
            res.sendStatus(500);
        }
    });
});

app.listen(80);

您可以运行此程序,向/file 发出请求,并看到浏览器提示您保存文件,保存该文件,然后在编辑器中打开该文件并查看数据是来自 google 的 HTML 页面。 com.

【讨论】:

    猜你喜欢
    • 2016-10-18
    • 2011-02-20
    • 1970-01-01
    • 2012-11-22
    • 1970-01-01
    • 2019-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多