简体   繁体   English

从NodeJS中的服务器下载文件

[英]File download from server in NodeJS

I have my REST service in Java and it has a endpoint which sends a file to the client (HTTP GET, /file). 我有Java的REST服务,它有一个端点,该端点将文件发送到客户端(HTTP GET,/ file)。 My front end client is in NodeJS. 我的前端客户端在NodeJS中。 I am not able to download the file from the REST service. 我无法从REST服务下载文件。 I can only store the file at a particular location, but I want to have a download dialogue box where the user can store the file (just like any other download dialogue box). 我只能将文件存储在特定位置,但是我想有一个下载对话框,用户可以在其中存储文件(就像其他任何下载对话框一样)。 My NodeJS code is as below: 我的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');
            }
        });
    });
});

The file is saved statically on the location /home/files/presentation.pcap . 该文件静态保存在/home/files/presentation.pcap位置。

My REST service side response is like below: 我的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();

And the result which I get on the NodeJS side is just like an alert box with the file contents in it. 我在NodeJS端得到的结果就像一个带有文件内容的警告框。 See output below: 请参见下面的输出:

在此处输入图片说明

Can anyone please let me know what mistake I am doing here. 谁能让我知道我在这里犯什么错误。 I would like to have download dialogue box when the user clicks on the Download button. 当用户单击“下载”按钮时,我希望有一个下载对话框。 When clicking the download button, a call should go to the REST service which in turn will send the file to the NodeJS front end and a dialogue box will open, which will ask the user for the location. 单击下载按钮时,应调用REST服务,该服务会将文件发送到NodeJS前端,然后会打开一个对话框,询问用户位置。

My Call from HTML is like below 我的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);
            });

          }

res.download() doesn't take in data. res.download()不接收数据。 It takes a file path. 它需要一个文件路径。

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

You want to call res.download within a successful fs.writeFile callback 您要在成功的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
    }
});

Update 更新

If you are using an ajax request, its not possible to download a file this way. 如果您使用的是ajax请求,则无法以这种方式下载文件。 Browsers make it impossible to make downloads through ajax requests. 浏览器无法通过ajax请求进行下载。

What you will want to do is just use the url to download the file in an anchor element. 您将要做的只是使用url在锚元素中下载文件。

HTML HTML

<a class="button" href="http://localhost:3000/openFile" target="_blank">Get request</a>

If you need to do it progmatically with javascript, you can use the window.open() method. 如果您需要使用javascript进行编程,则可以使用window.open()方法。

Javascript 使用Javascript

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

I used jQuery in this example but I think it illustrates what needs to be done. 我在此示例中使用了jQuery,但我认为它说明了需要完成的工作。 The window.open part is the important part. window.open部分是重要的部分。

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

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