使用AngularJS从Node.JS服务器下载文件

前端之家收集整理的这篇文章主要介绍了使用AngularJS从Node.JS服务器下载文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想从运行NodeJS的服务器上用我的浏览器下载文件.
在服务器端,为了提供我有的文件
  1. exports.download = function(req,res) {
  2. var filename = "33.jpg";
  3. var filePath = path.join(__dirname,'..','downloads',filename);
  4. var stat = fs.statSync(filePath);
  5.  
  6. var fileToSend = fs.readFileSync(filePath);
  7.  
  8. res.writeHead(200,{
  9. 'Content-Type': 'image/jpeg','Content-Length': stat.size,'Content-Disposition': filename
  10. });
  11. res.end(fileToSend);
  12. };

名为33.jpg的文件存在,大小为744Kb.来自客户的电话很有效

在AngularJS的客户端,这里是我如何调用post调用获取文件(目前不使用参数uri):

  1. $scope.downloadTrack = function(uri) {
  2. $http.post('/api/files/download',{uri: uri}).then(function(response) {
  3. var blob = new Blob([response.data],{ type: 'image/jpeg' });
  4. var fileName = response.headers('content-disposition');
  5. saveAs(blob,fileName);
  6. },function(response) {
  7. console.log('Download error');
  8. console.log(response);
  9. });
  10. }

标题是好的(我可以检索文件名)

我的问题是下载了一个文件,但是大小为1.5Mb并且不可读.我尝试了不同的流方法,将数据附加到响应,管道等,但没有成功.
另一点(不确定是否重要):在Safari中打开文件显示损坏的图标,在Chrome中保存文件

PS:如果信息有用,我和Yeoman一起创建了这个项目

谢谢大家

[更新]
新版服务器功能(仍然无法正常工作)

  1. exports.download = function(req,filename);
  2. var stat = fs.statSync(filePath);
  3. var fileToSend = fs.readFileSync(filePath);
  4. res.set('Content-Type','image/jpeg');
  5. res.set('Content-Length',stat.size);
  6. res.set('Content-Disposition',filename);
  7. res.send(fileToSend);
  8. };

[更新2]
double size文件文件随机包含额外的“efbffd”char序列,使其无法读取

通过设置为blob的响应类型的定义解决了问题
  1. $http({
  2. url: '/api/files/download',method: "POST",data: {
  3. uri: uri
  4. },responseType: 'blob'
  5. }).then(function (response) {
  6. var data = response.data;
  7. var headers = response.headers;
  8. var blob = new Blob([data],{ type: 'audio/mpeg' });
  9. var fileName = headers('content-disposition');
  10. saveAs(blob,fileName);
  11. }).catch(function (response) {
  12. console.log('Unable to download the file')
  13. });

猜你在找的Angularjs相关文章