2016-10-16 34 views
0

我在Java中有我的REST服务,它有一个将文件发送到客户端(HTTP GET,/ file)的端点。我的前端客户端在NodeJS中。我无法从REST服务下载文件。我只能将文件存储在特定的位置,但我希望有一个下载对话框供用户存储文件(就像任何其他下载对话框一样)。我的代码的NodeJS是如下:从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的结果就像是在它的文件内容的警告框。请参见下面的输出:

enter image description here

任何人都可以请让我知道我在做什么错在这里。我想在用户点击下载按钮时有下载对话框。点击下载按钮时,应该打电话给REST服务,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); 
      }); 

      } 
+0

你是如何提出要求的?它是通过ajax还是只是在您的网站上的下载链接。 – JoeMoe1984

+0

是的,它通过ajax ...更新我的问题与HTML部分 –

回答

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做progmatically,你可以使用window.open()方法。

的Javascript

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

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

+0

你是否看到从您的终端“完成”日志? – JoeMoe1984

+0

是的,我能够看到日志完成。并且该文件存储在静态位置。 –

+0

该代码正在为我工​​作。我调整了res.download参数,并添加了一个回调函数以防错误。当您运行该代码时,您是否看到任何打印到控制台的“出错了”? – JoeMoe1984