我是 Node 的初学者,我试图弄清楚如何在服务器上创建一个 zip 文件,然后将其发送到客户端,然后将 zip 文件下载到用户的浏览器。我正在使用 Express 框架,并且正在使用 Archiver 来实际进行压缩。我的服务器代码如下,取自Dynamically create and stream zip to client
router.get('/image-dl', function (req,res){
res.writeHead(200, {
'Content-Type': 'application/zip',
'Content-disposition': 'attachment; filename=myFile.zip'
});
var zip = archiver('zip');
// Send the file to the page output.
zip.pipe(res);
// Create zip with some files. Two dynamic, one static. Put #2 in a sub folder.
zip.append('Some text to go in file 1.', { name: '1.txt' })
.append('Some text to go in file 2. I go in a folder!', { name: 'somefolder/2.txt' })
.finalize();
});
所以它压缩两个文本文件并返回结果。在客户端,我在服务中使用以下函数来实际调用该端点
downloadZip(){
const headers = new Headers({'Content-Type': 'application/json'});
const token = localStorage.getItem('token')
? '?token=' + localStorage.getItem('token')
: '';
return this.http.get(this.endPoint + '/job/image-dl' + token, {headers: headers})
.map((response: Response) => {
const result = response;
return result;
})
.catch((error: Response) => {
this.errorService.handleError(error.json());
return Observable.throw(error.json());
});
}
然后我有另一个函数调用downloadZip()
并实际将 zip 文件下载到用户的本地浏览器。
testfunc(){
this.jobService.downloadZip().subscribe(
(blah:any)=>{
var blob = new Blob([blah], {type: "application/zip"});
FileSaver.saveAs(blob, "helloworld.zip");
}
);
}
当testfunc()
被调用时,一个 zip 文件会下载到用户的浏览器,但是当我尝试解压缩它时,它会创建一个 zip.cpgz 文件,然后在无限循环中单击该文件时会变成一个 zip 文件,这表明发生了某种损坏。谁能看到我在这里出错的地方?