小编Pi *_*ver的帖子

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

我想从运行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) …
Run Code Online (Sandbox Code Playgroud)

binary download node.js angularjs

6
推荐指数
1
解决办法
9125
查看次数

标签 统计

angularjs ×1

binary ×1

download ×1

node.js ×1