[英]Compressing File Uploaded From Multer using Nodejs Zlib
我正在尝试使用 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)
}
})
这会将压缩文件添加到压缩目录中,但尝试解压缩它会引发错误。
我可以使用另一种方法来使用 zlib 压缩此文件吗?
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.