简体   繁体   English

Node js从服务器提供文件主体并在浏览器中下载

[英]Node js serve file body from server and download in browser

I have a file repository and when i call it from the browser it automatically downloads the file and this is fine. 我有一个文件存储库,当我从浏览器中调用它时,它会自动下载文件,这很好。 But i want to do this request on my server, and then serve the file result to the browser. 但我想在我的服务器上执行此请求,然后将文件结果提供给浏览器。 Here is the example of the get request from my server. 这是从我的服务器获取请求的示例。

downloadFile(req , res , next) {
    let options = {
         url: 'url to my file repo',
    };

    request(options, function (err, resp, body) {
       if (err) {
           res.status(500).send("");
           return
       }

       for (const header in resp.headers) {
           if (resp.headers.hasOwnProperty(header)) {
               res.setHeader(header, resp.headers[header]);
           }
       }
       resp.pipe(res);
    })
}

The request is working fine, and when i access my server from the browser it starts downloading the file. 该请求工作正常,当我从浏览器访问服务器时,它开始下载文件。 Everything seems to work fine except one thing, the file can't be opened. 除了一件事以外,其他所有东西似乎都可以正常工作,无法打开文件。 This file format can't be opened , says me the image player (if the file is image for example). 图像播放器说, 无法打开此文件格式 (例如,如果文件是图像)。 Where is the problem, Is it the way i serve the file from the server? 问题出在哪里,这是我从服务器提供文件的方式吗? Thank you in advance. 先感谢您。 I lost a lot of time and can't find the solution. 我浪费了很多时间,找不到解决方案。

Because what you probably want to send is the body of the request (eg the data of your image). 因为您可能要发送的是请求的主体(例如,图像数据)。 So instead of resp.pipe(res): 因此,而不是resp.pipe(res):

res.send(body)

Use the developer mode of your browser to check the network messages passing between the server and your browser. 使用浏览器的开发人员模式检查在服务器和浏览器之间传递的网络消息。

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

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