最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

下载客户端服务器发送的zip文件?

运维笔记admin11浏览0评论

下载客户端服务器发送的zip文件?

下载客户端服务器发送的zip文件?

我有一个从AWS S3下载多个文件的API,创建一个保存到磁盘的zip,然后将该zip发送回客户端。 API有效,但我不知道如何在客户端处理响应/下载zip到磁盘。

这是我的API:

reports.get('/downloadMultipleReports/:fileKeys', async (req, res) => {

  var s3 = new AWS.S3();
  var archiver = require('archiver');

  const { promisify } = require('util');

  var str_array = req.params.fileKeys.split(',');

  console.log('str_array: ',str_array);

  for (var i = 0; i < str_array.length; i++) {

    var filename = str_array[i].trim();
    var filename = str_array[i];
    var localFileName = './temp/' + filename.substring(filename.indexOf("/") + 1);

    console.log('FILE KEY >>>>>>  : ', filename);

    const params = { Bucket: config.reportBucket, Key: filename };

    const data = await (s3.getObject(params)).promise();

    const writeFile = promisify(fs.writeFile);

    await writeFile(localFileName, data.Body);
  }

    // create a file to stream archive data to.
    var output = fs.createWriteStream('reportFiles.zip');
    var archive = archiver('zip', {
      zlib: { level: 9 } // Sets the compression level.
    });

    // listen for all archive data to be written
    // 'close' event is fired only when a file descriptor is involved
    output.on('close', function() {
      console.log(archive.pointer() + ' total bytes');
      console.log('archiver has been finalized and the output file descriptor has closed.');
    });

    // This event is fired when the data source is drained no matter what was the data source.
    // It is not part of this library but rather from the NodeJS Stream API.
    // @see: .html#stream_event_end
    output.on('end', function() {
      console.log('Data has been drained');
    });

    // good practice to catch warnings (ie stat failures and other non-blocking errors)
    archive.on('warning', function(err) {
      if (err.code === 'ENOENT') {
        // log warning
      } else {
        // throw error
        throw err;
      }
    });

    // good practice to catch this error explicitly
    archive.on('error', function(err) {
      throw err;
    });

    // pipe archive data to the file
    archive.pipe(output);

    // append files from a sub-directory, putting its contents at the root of archive
    archive.directory('./temp', false);

    // finalize the archive (ie we are done appending files but streams have to finish yet)
    // 'close', 'end' or 'finish' may be fired right after calling this method so register to them beforehand
    archive.finalize();

    output.on('finish', () => {

      console.log('Ding! - Zip is done!');

      const zipFilePath =  "./reportFiles.zip" // or any file format

      // res.setHeader('Content-Type', 'application/zip');

      fs.exists(zipFilePath, function(exists){

        if (exists) {     
          res.writeHead(200, {
            "Content-Type": "application/octet-stream",
            "Content-Disposition": "attachment; filename=" + "./reportFiles.zip"
          });
          fs.createReadStream(zipFilePath).pipe(res);

        } else {
          response.writeHead(400, {"Content-Type": "text/plain"});
          response.end("ERROR File does not exist");
        }

      });
    });

  return;
});

这就是我调用API /期望下载响应的方式:

  downloadMultipleReports(){

    var fileKeysString = this.state.awsFileKeys.toString();
    var newFileKeys = fileKeysString.replace(/ /g, '%20').replace(/\//g, '%2F');

    fetch(config.api.urlFor('downloadMultipleReports', { fileKeys: newFileKeys }))
    .then((response) => response.body())

    this.closeModal();
  }

如何处理响应/将zip下载到磁盘?

回答如下:

这最终为我工作:

服务器端:

const zipFilePath =  "./reportFiles.zip";

      fs.exists(zipFilePath, function(exists){

        if (exists) {     
          res.writeHead(200, {
            "Content-Type": "application/zip",
            "Content-Disposition": "attachment; filename=" + "./reportFiles.zip"
          });
          fs.createReadStream(zipFilePath).pipe(res);

        } else {
          response.writeHead(400, {"Content-Type": "text/plain"});
          response.end("ERROR File does not exist");
        }

      });

客户端:

  downloadMultipleReports(){

    var fileKeysString = this.state.awsFileKeys.toString();
    var newFileKeys = fileKeysString.replace(/ /g, '%20').replace(/\//g, '%2F');

    fetch(config.api.urlFor('downloadMultipleReports', { fileKeys: newFileKeys }))
    .then((res) => {return res.blob()})
    .then(blob =>{
      download(blob, 'reportFiles.zip', 'application/zip');
      this.setState({isOpen: false});
    })
  }
发布评论

评论列表(0)

  1. 暂无评论