NodeJS 从服务器下载文件

arp*_*shi 4 javascript rest node.js express

我有 Java 中的 REST 服务,它有一个端点将文件发送到客户端(HTTP GET、/file)。我的前端客户端是 NodeJS。我无法从 REST 服务下载该文件。我只能将文件存储在特定位置,但我想要一个下载对话框,用户可以在其中存储文件(就像任何其他下载对话框一样)。我的NodeJS代码如下:

router.get('/openFile',function(req,res){
    native_data_retrieval_rest_client.get("http://localhost:8080/file?fileName=presentation.pcap",function(data){
        var fileName="/home/files/presentation.pcap";
        res.download(data);//This doesnt open dialogue box 

        fs.writeFile(fileName, data, function (err) {
            if (err) {
                //Error handling
            } else {
                console.log('Done');
            }
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

该文件静态保存在该位置/home/files/presentation.pcap

我的 REST 服务端响应如下:

response.setHeader("Content-Disposition", "attachment; filename="
                    + fileName);
            response.setHeader("Content-Type", type);

            reportBytes = new byte[131072];// New change
            OutputStream os = response.getOutputStream();// New change
            int read = 0;
            while ((read = inputStream.read(reportBytes)) != -1) {
                os.write(reportBytes, 0, read);
            }
            //System.out.println("Bytes sent" + reportBytes);
            os.flush();
            os.close();
Run Code Online (Sandbox Code Playgroud)

我在 NodeJS 端得到的结果就像一个警告框,其中包含文件内容。请参阅下面的输出:

在此输入图像描述

谁能告诉我我在这里犯了什么错误。我希望当用户单击“下载”按钮时有下载对话框。单击下载按钮时,应调用 REST 服务,该服务进而将文件发送到 NodeJS 前端,并打开一个对话框,询问用户位置。

我的 HTML 调用如下所示

tr.append("td").append("button")
.on("click", function(){

           openFile();
          })

 function openFile(){
          alert("button clicked");

          $http.get('/openFile/').success(function(response) {
              console.log(response.response);
           }).error(function(error){
              alert(error);
            });

          }
Run Code Online (Sandbox Code Playgroud)

Joe*_*984 5

res.download() 不接收数据。它需要一个文件路径。

http://expressjs.com/en/api.html#res.download

您想在成功的 fs.writeFile 回调中调用 res.download

var fileName = "presentation.pcap";
var filePath = "/home/files/" + fileName;

fs.writeFile(filePath, data, function (err) {
    if (err) {
        //Error handling
    } else {
        console.log('Done');
        res.download(filePath, fileName, function(err) {
            console.log('download callback called');
            if( err ) {
                console.log('something went wrong');
            }

        }); // pass in the path to the newly created file
    }
});
Run Code Online (Sandbox Code Playgroud)

更新

如果您使用 ajax 请求,则无法通过这种方式下载文件。浏览器无法通过 ajax 请求进行下载。

您要做的只是使用 url 下载锚元素中的文件。

超文本标记语言

<a class="button" href="http://localhost:3000/openFile" target="_blank">Get request</a>
Run Code Online (Sandbox Code Playgroud)

如果您需要使用 javascript 以编程方式执行此操作,可以使用 window.open() 方法。

JavaScript

$('.button').click(function(e) {
    e.preventDefault();
    window.open('http://localhost:3000/openFile', '_blank');
});
Run Code Online (Sandbox Code Playgroud)

我在这个例子中使用了 jQuery,但我认为它说明了需要做什么。window.open 部分是重要的部分。