2015-11-25 35 views
3

我一直在尋找一些答案,但我沒有成功。如何從Node.js下載AngularJs控制器中的.docx文件

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

我從angularjs發送一個帖子到我的/ api/generateReport與一些數據,我生成這個.docx,但我不能設法發送它。 將文件放置在/ public dir中是不可取的,也不安全,但如果將文件放在/ public dir中,並且我將文件路徑提供給AngularJs,則無法下載。

我讀過關於blob和其他的東西,但我無法管理下載.docx文件。

PS:我使用$資源指令來處理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) 
 
    ); 
 
    } 
 
);

+0

你看過可能發送的文件緩衝區嗎? Browserify支持瀏覽器端緩衝區,所以它是與nodejs端相同類型的緩衝區,但您可以將它發送到緩衝區,然後將其翻譯回瀏覽器端的文檔 – Binvention

回答

0

我建議下載頭添加到您的文件,並使用超鏈接(<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); 
}); 
+0

嗨,感謝您的回覆。但我需要通過angularjs控制器處理請求,因爲我需要發佈一些數據,所以我不能直接使用href。 –