1

前端是用ReactJS编写的,更具体地说是grommet单击“下载”按钮可向用户提供多个pdf文件。这些文件存储在GridFS中。我希望给用户一个包含所有这些文件的压缩文件夹。我怎样才能做到这一点?

提前致谢。

4

1 回答 1

1

我有!!使用归档器的超级简单解决方案。第一次工作。

注意:我使用的是sails.jsDBFile是我的模特。

const GridFsAdapter = require('../adapters/gridfs-adapter');
const archiver = require('archiver');

async function downloadMultiple (query, res, filename) {

  // create a stream for download
  const archive = archiver('zip', {
    zlib: {level: 9} // Sets the compression level.
  });

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

  archive.on('error', (err) => {
    throw err;
  });

  // set file name
  res.attachment(filename);
  
  // pipe the stream to response before appending files/streams
  archive.pipe(res);

  // add your streams
  await DBFile
    .stream(query)
    // like mongoDBs cursor.forEach() function. Avoids to have all record in memory at once
    .eachRecord(async (dbFile) => {
      // get the stream from db
      const {stream, data} = await GridFsAdapter().read(dbFile.fileId);
      // append stream including filename to download stream
      archive.append(stream, {name: data.filename});
    });

  // tell the download stream, you have all your files added
  archive.finalize();
}

于 2020-07-02T08:17:54.063 回答