简体   繁体   English

从服务器下载文件

[英]Download files from server

All files downloaded are corrupted.下载的所有文件都已损坏。 I saw in some tutorials saying that this is caused by the passing from backend to frontend, the data will be transformed.我在一些教程中看到,这是由后端到前端的传递引起的,数据将被转换。 But I don't know how to pass the file from backend to frontend.但我不知道如何将文件从后端传递到前端。 Appreciate any help given.感谢您提供的任何帮助。 Forgive me if it's a silly question.如果这是一个愚蠢的问题,请原谅我。 This is my first question.这是我的第一个问题。

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

Here's my code Server Side:这是我的代码服务器端:

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

Client Side:客户端:

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

Try this one试试这个

Server服务器

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

Client客户

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM