【发布时间】:2018-02-07 20:53:07
【问题描述】:
目前,我正在使用 multer 库将文件保存在文件系统上。此应用程序正在使用 Node 和 Express。
我可以先将文件保存在服务器上,然后再加密。稍后删除未加密的文件。但是,我不想直接在服务器上添加未加密的文件。所以,我正在寻找一种方法来加密从前端传入的文件,然后将其保存到磁盘。
const defaultFolder = 'upload';
const filePath = resolveHome(process.env.FILE_STORAGE_LOCATION || defaultFolder);
const key = 'test';
const cipher = crypto.createCipher('aes-256-cbc', key);
const decipher = crypto.createDecipher('aes-256-cbc', key);
const upload = multer({
storage: multer.diskStorage({
destination: filePath,
filename: (req, file, cb) => {
const parts = file.originalname.split('.');
const ext = parts.pop();
const name = parts.join('.');
cb(null, name + '-' + Date.now() + '.' + ext);
},
}),
}).single('file');
app.post('/upload', (req, res) => {
upload(req, res, err => {
if (err) {
return res.status(400).send({
error: 'The request was invalid',
fileName: req.file.originalname,
});
}
return res.status(200).send({
fileName: req.file.filename,
});
});
});
我尝试使用 crypto 库来加密文件,但它不起作用。我认为 req.cipher 无效,因为我通常会使用 req.file 来获取对该文件的引用。
app.post('/upload', (req, res) => {
upload(req, res, err => {
output = fs.createWriteStream(filePath + '/' + req.file.originalname);
req.pipe(cipher).pipe(output).on('finish', () => console.log('Encrypted file written on disk'));
if (err) {
return res.status(400).send({
error: 'The request was invalid',
fileName: req.file.originalname,
});
}
return res.status(200).send({
fileName: req.file.originalname,
});
});
});
我试图只写文件而不使用密码并且文件是空的。添加此信息以防万一。
req.pipe(output).on('finish', () => console.log('Encrypted file written on disk'));
【问题讨论】:
-
它是否产生任何错误消息?
-
不,没有错误信息。
标签: javascript node.js express encryption multer