简体   繁体   中英

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:

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?

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:


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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