Pi *_*ver 6 binary download node.js angularjs
我想从运行NodeJS的服务器上用我的浏览器下载文件.在服务器端,为了提供我有的文件:
exports.download = function(req, res) {
var filename = "33.jpg";
var filePath = path.join(__dirname, '..', '..', 'downloads', filename);
var stat = fs.statSync(filePath);
var fileToSend = fs.readFileSync(filePath);
res.writeHead(200, {
'Content-Type': 'image/jpeg',
'Content-Length': stat.size,
'Content-Disposition': filename
});
res.end(fileToSend);
};
Run Code Online (Sandbox Code Playgroud)
名为33.jpg的文件存在,大小为744Kb.来自客户的电话很有效
在AngularJS的客户端,这里是我如何调用post调用来获取文件(目前不使用参数uri):
$scope.downloadTrack = function(uri) {
$http.post('/api/files/download', {uri: uri}).then(function(response) {
var blob = new Blob([response.data], { type: 'image/jpeg' });
var fileName = response.headers('content-disposition');
saveAs(blob, fileName);
}, function(response) {
console.log('Download error');
console.log(response);
});
}
Run Code Online (Sandbox Code Playgroud)
标题是好的(我可以检索文件名)
我的问题是下载了一个文件,但是大小为1.5Mb并且不可读.我尝试了不同的流方法,将数据附加到响应,管道等,但没有成功.另一点(不确定是否重要):在Safari中打开文件并显示损坏的图标,在Chrome中保存文件
PS:如果信息有用,我和Yeoman一起创建了这个项目
谢谢大家
[更新] 新版服务器功能(仍无法正常工作)
exports.download = function(req, res) {
var filename = "33.jpg";
var filePath = path.join(__dirname, '..', '..', 'downloads', filename);
var stat = fs.statSync(filePath);
var fileToSend = fs.readFileSync(filePath);
res.set('Content-Type', 'image/jpeg');
res.set('Content-Length', stat.size);
res.set('Content-Disposition', filename);
res.send(fileToSend);
};
Run Code Online (Sandbox Code Playgroud)
[更新2] 双倍大小的文件在文件中随机包含额外的"efbffd"字符序列,使其无法读取
Pi *_*ver 10
通过设置为blob的响应类型的定义解决了问题
$http({
url: '/api/files/download',
method: "POST",
data: {
uri: uri
},
responseType: 'blob'
}).then(function (response) {
var data = response.data;
var headers = response.headers;
var blob = new Blob([data], { type: 'audio/mpeg' });
var fileName = headers('content-disposition');
saveAs(blob, fileName);
}).catch(function (response) {
console.log('Unable to download the file')
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
9125 次 |
最近记录: |