簡體   English   中英

如何從Node.js下載AngularJs控制器中的.docx文件

[英]How to download a .docx file in AngularJs controller from Node.js

我一直在尋找stackoverflow的答案,但我沒有成功。

我在路由中有一個node.js方法,它使用docxtemplater庫從另一個模板生成.docx模板。

我發送了一個從angularjs到我的/ api / generateReport的帖子和一些數據,我生成了這個.docx,但我無法設法發送它。 不建議也不安全將文件放在/ public目錄中,但如果我將文件放在/ public目錄中並且我提供AngularJs的文件路徑,則無法下載。

我已經閱讀了關於blob和其他內容但我無法下載.docx文件。

PS:我正在使用$ resource指令來處理api請求,我已經將responseType設置為arrayBuffer

 angular.module('MyApp') .factory('GenerateReport', function($http, $location,$resource, $rootScope, $alert, $window) { return $resource("/api/GenerateReport/:id",{}, { 'query': { method: 'GET', isArray: false }, responseType: 'arrayBuffer' }); }); 

我以這種方式發送回復。

 var fileDocx = fs.readFileSync(__base + "/plantillaSalida.docx", "binary");
 res.send(fileDocx);

角度控制器收到響應:

 GenerateReport.save({ projectExecution: $scope.projectExecution, auditingProject: $scope.auditingProject, participants: $scope.participants, exampleProjects: $scope.exampleProjects }, function(response) { /***What to to here??***/ $mdToast.show( $mdToast.simple() .content('Informe generado') .position('bottom right left') .hideDelay(3000) ); }, function(error) { console.log("error"); $mdToast.show( $mdToast.simple() .content('Error al general el informe') .position('bottom right left') .hideDelay(3000) ); } ); 

我建議將下載標題添加到您的文件中,並使用超鏈接鏈接它( <a href="/download">

var path = require('path');
var mime = require('mime');

app.get('/download', function(req, res){

  var file = __base + "/plantillaSalida.docx";

  var filename = path.basename(file);
  var mimetype = mime.lookup(file);

  res.setHeader('Content-disposition', 'attachment; filename=' + filename);
  res.setHeader('Content-type', mimetype);

  var filestream = fs.createReadStream(file);
  filestream.pipe(res);
});

如果您使用快速使用下面的代碼

app.get('/download', function(req, res){
    var file = __base + "/plantillaSalida.docx";
    var filename = path.basename(file);
    res.setHeader('Content-disposition', 'attachment; filename=' + filename);
    res.download(file); 
 });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM