-1

下载的所有文件都已损坏。我在一些教程中看到说这是由于从后端传递到前端造成的,数据将被转换。但我不知道如何将文件从后端传递到前端。感谢提供的任何帮助。如果这是一个愚蠢的问题,请原谅我。这是我的第一个问题。

https://stackoverflow.com/questions/33789241/file-download-giving-corrupt-file-in-nodejs

这是我的代码服务器端:

@Post('downloadDB')
    @Header('Content-Type', 'application/octet-stream')
    @Header('Content-Disposition',`attachment; filename=123`)
    async downloadDB(@Res() res: Response) {
        try {
            const zip = new AdmZip();
 
            zip.addLocalFile("/path/to/file.db");
        
            // Define zip file name
            const downloadName = `${Date.now()}abc.zip`;
        
            const data = zip.toBuffer();
        
            // save file zip in root directory
            zip.writeZip(__dirname+"/"+downloadName);
            
            
            res.setHeader('Content-Disposition', `attachment; filename=${downloadName}`);
            res.setHeader('Content-type', "application/zip");
            var stream = fs.createReadStream(__dirname+"/"+downloadName);
            res.download(__dirname+"/"+downloadName);
            
        } catch (e) {
            console.error(e)
            res.status(500).end();
        }
    }

客户端:

axios.post(
        '/api/v1/config/downloadDB', 
        { responseType: 'blob' },
        {headers: {
            'Content-Type': 'multipart/form-data',
            'responseType': 'arraybuffer'
        }}
    ).then(function (response) {
        if (response.data.error) {
            console.error(response.data.error)
        }
        const disposition = response.request.getResponseHeader('Content-Disposition');
        var filename = "";
        var filenameRegex = /filename[^;=n]*=((['"]).*?2|[^;n]*)/;
        var matches = filenameRegex.exec(disposition);
        if (matches != null && matches[1]) {
            filename = matches[1].replace(/['"]/g, '');
        }
        let blob = new Blob([response.data], {type: 'application/zip'});
        const downloadUrl = URL.createObjectURL(blob);
        let a = document.createElement('a');
        a.href = downloadUrl;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        a.remove();
4

1 回答 1

0

试试这个

服务器

app.post('/imageDownload', async(req, res) => {
 const admzip = require('adm-zip')
 var zip = new admzip();
 var outputFilePath = Date.now() + "output.zip";
 zip.addLocalFile('imagepath')
 fs.writeFileSync(outputFilePath, zip.toBuffer());
 res.download(outputFilePath,(err)=>{
  if(err)
   console.log(err)
 }
})

客户

axios({
    url: `/imageDownload`,
    method: 'POST',
    responseType: 'blob',
}).then((response) => {
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', 'filename.zip'); 
      document.body.appendChild(link);
      link.click();
});
于 2021-07-21T05:29:36.380 回答