简体   繁体   English

Express – 从外部 URL 下载文件

[英]Express – download file from an external URL

I have a file stored on an external server.我有一个文件存储在外部服务器上。 I want to be able to call GET request to my own NodeJS server (using express ).我希望能够向我自己的 NodeJS 服务器调用GET请求(使用express )。 What I'm currently doing is almost OK, but it does not trigger browser to download the file (no browser UI for the download is shown):我目前正在做的几乎可以,但它不会触发浏览器下载文件(没有显示用于下载的浏览器 UI):

const express = require('express');

const app = express();

app.get('/download-file', (req, res) => {
  const externalRequest = http.request({
    hostname: 'my.external-server.com',
    path: '/my/path/my-file.zip',
  }, (externalRes) => {
    res.setHeader('Content-Disposition', 'attachment; filename="MyFile.zip"');
    externalRes.pipe(res);
  });
  return externalRequest.end();
});

app.listen(8080, () => console.log('Server is listening'));

What am I missing here?我在这里缺少什么? I see that triggering a GET request to localhost:8080/download-file is actually fetching it, but no UI for download is shown.我看到触发对localhost:8080/download-file的 GET 请求实际上是在获取它,但没有显示用于下载的 UI。

This is the code that is running in one of my pet projects, hope it helps.这是在我的一个宠物项目中运行的代码,希望它有所帮助。

It pipes the download request ok, but there is no size info for the download, so it becames one of that downloads that you dont know when will finish.它通过管道传输下载请求,但没有下载的大小信息,因此它成为您不知道何时完成的下载之一。

const http = require('http')

app.get('/down_file/:file_name', (req, res) => {

    const fileName = req.params.file_name
    const url = "http://externalUrl/" + fileName

    var externalReq = http.request(url, function(externalRes) {
        res.setHeader("content-disposition", "attachment; filename=" + fileName);
        externalRes.pipe(res);
    });
    externalReq.end();
})

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

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