【问题标题】:File download from server in NodeJS在 NodeJS 中从服务器下载文件
【发布时间】:2017-02-25 05:19:58
【问题描述】:

我在 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');
            }
        });
    });
});

文件静态保存在位置/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();

我在 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);
            });

          }

【问题讨论】:

  • 您是如何提出请求的?是通过 ajax 还是只是您网站上的下载链接。
  • 是的,它通过 ajax ...用 HTML 部分更新了我的问题

标签: javascript node.js rest express


【解决方案1】:

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
    }
});

更新

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

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

HTML

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

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

Javascript

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

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

【讨论】:

  • 您是否从终端看到“完成”日志?
  • 是的,我可以在日志上看到完成的内容。而且文件也存储在静态位置。
  • 代码对我有用。我调整了 res.download 参数并添加了一个回调函数以防出错。当您运行该代码时,您是否看到任何打印到控制台的“出现问题”?
  • 做了同样的事,但没有下载框
  • fs.writeFile(fileName, data, function (err) { if (err) { //错误处理 } else { console.log('Done'); res.download(fileName,"presentation .pcap",function(error){ if(error){ console.log(error); }else{ console.log("downloaded"); } }); } });
猜你喜欢
  • 2015-08-28
  • 1970-01-01
  • 2015-06-14
  • 2019-03-30
  • 1970-01-01
  • 2013-09-23
  • 2013-12-14
相关资源
最近更新 更多