从服务器下载文件

Download files from server

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

这是我的代码 服务器端:

@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();

试试这个

服务器

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();
});