【发布时间】: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