使用angular和express JS下载所有文件格式 [英] download all file formats using angular and express JS
问题描述
我正在用angular js下载所有文件格式.使用已有的代码,我可以下载文本格式.但是对于所有其他格式,我无法打开下载的文件.我的REST服务提供响应 content-type:application/octet-stream
.我的代码库使用 content-type:application/json
调用express.js的res.send(body)方法.下载的图像大小增加了一倍.另外,我可以看到主体的类型是字符串.
I'm working on downloading all file formats in angular js. With the code piece I have, I can download text formats. But for all the other formats, I am not able to open the downloaded files. My REST service gives response content-type: application/octet-stream
. My codebase calls res.send(body) method of express.js, with content-type:application/json
. The downloaded image size is doubled. Also, I could see the type of the body is string.
如果要请求,我尝试使用 content-type:application/octet-stream
调用express.js的 res.download(路径,文件名,回调)
函数是下载电话.这是正确的方法吗?另外,我不确定在 res.download
函数中发送哪个路径,因为该文件来自服务器端.请帮助我.
I am trying to invoke res.download(path, filename, callback)
function of express.js with content-type:application/octet-stream
if the request is download call. Is it a correct approach? Also I am not sure which path to send in res.download
function, as the file comes from the server end. Kindly help me on this.
我的客户代码:
$scope.downloadFile = function(key) {
service.downloadFile().then(function(result) {
var blob = new Blob([result], {
type: 'application/octet-stream; charset=utf-8'
});
var urlCreator = window.URL || window.webkitURL || window.mozURL || window.msURL;
var url = urlCreator.createObjectURL(blob);
var element = angular.element('<a/>');
element.attr({
href: url,
target: '_blank',
download: key
})[0].click();
});
}
推荐答案
我的一位同事共享了一个链接,该链接解决了我的问题.有一种方法可以直接代理传入的流.有关详细信息,请参见 https://github.com/request/request
One of my colleague shared a link which resolved my problem. There is way to proxy the incoming stream directly. This detail is available in https://github.com/request/request
req.pipe(request('url')).pipe(resp)
使用此流,客户端可以使用流,客户端可以调用链接/URL来利用附件.
With this the stream can be made available to client and client can invoke the link/url to avail the attached file.
客户代码:
$scope.downloadFile = function(key) {
var url = 'http://localhost:8080/getFile';
var element = angular.element('<a/>');
element.attr({
href: url,
target: '_blank',
download: fileName
})[0].click();
});
}
这篇关于使用angular和express JS下载所有文件格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!