简体   繁体   English

使用 Nodejs Zlib 压缩从 Multer 上传的文件

[英]Compressing File Uploaded From Multer using Nodejs Zlib

I am trying to compress an uploaded file using nodejs zlib.The compression works but trying to uncompress it throws an error.I created a compress route which is a post request to upload the file to be compressed:我正在尝试使用 nodejs zlib 压缩上传的文件。压缩有效,但尝试解压缩会引发错误。我创建了一个压缩路由,它是上传要压缩文件的发布请求:

app.post('/compress', upload.single('file'), (req, res) => {
  try {
    var streamInstance = new stream.Readable();
    const destination = createWriteStream(`compressed/${req.file.originalname}.gz`);
    const source = streamInstance.push(Buffer.from(JSON.stringify(req.file)))
    res.json(source)
    streamInstance.push(null);
    pipeline(source, gzip, destination, (err, file) => {
      if (err) {
        console.log(err)
        return res.json('An error occurred:', err);
      } else {
        console.log({
          file: file
        })
        return res.json(file)

      }
    })
  } catch (err) {
    console.log(err)
    res.json(err)
  }
})

This add the compressed file in the compressed directory but trying to uncompress it throws an error.这会将压缩文件添加到压缩目录中,但尝试解压缩它会引发错误。

Is there another method i could use in compressing this file using zlib?我可以使用另一种方法来使用 zlib 压缩此文件吗?

Multer gives the ability to use the memoryStorage method.So you can get the actual buffer of that file.With that you can use this: Multer 提供了使用memoryStorage方法的能力。因此您可以获得该文件的实际缓冲区。您可以使用它:


var storage = multer.memoryStorage()
var upload = multer({
  storage: storage
})

app.post('/compress', upload.single('file'), async (req, res) => {
  try {
    const destination = `compressed/${req.file.originalname}.gz`;
    await zlib.gzip(req.file.buffer, async (err, response) => {
      if (err) {
        return res.status(500).json({error:err})
      } else {
        await fs.appendFile(path.join(__dirname,destination), response, (err, data) => {
          if (err) {
            return res.status(500).json({error:err})
          } else {
            res.download(path.join(__dirname,destination),`${req.file.originalname}.gz`);
          }
        })
      }
    })
  } catch (err) {
    console.log(err)
    res.json(err)
  }
})

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

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