2016-02-29 28 views
0

我想用archiver + express下載多個文件。服務器應發送.zip文件以響應來自客戶端的post請求。 下面的代碼創建一個zip存檔,發送它,顯示一個保存爲用戶對話框並讓他打開存檔。默認情況下,WinRAR打開裏面的檔案和列表文件(只有一個文件),用! 98I9ZOCR.zip:意外的檔案結束錯誤。 有什麼不對?nodejs + archiver,爲什麼這個zip壓縮文件下載器不起作用(意外的存檔結束)?

服務器:

var archive = archiver('zip'); 
    archive.on('error', function(err) { 
     res.status(500).send({error: err.message}); 
    }); 
    //on stream closed we can end the request 
    archive.on('end', function() { 
     console.log('Archive wrote %d bytes', archive.pointer()); 
    }); 
    //set the archive name 
    res.attachment('userarchive.zip'); 
    //this is the streaming magic 
    archive.pipe(res); 
    for (var fi in req.body.filename) { 
     var _file = src + '/' + req.body.filename[fi]; 
     archive.file(_file, { name: p.basename(_file) }); 
    } 
    archive.finalize(); 

客戶端:

$http({ 
     method: 'post', 
     url: to, 
     data: data 
    }).success(function(data, status, headers, config){ 
     var file = new Blob([data], {type: 'application/zip'}); 
     window.location = URL.createObjectURL(file); 
    }).error(function(data, status, headers, config){ 
     console.log('Error'); 
    }); 

回答

0

我忘了設置正確的反應類型: responseType: 'arraybuffer'

相關問題