使用Node.js保存到磁盘之前加密上载的文件

时间:2018-02-07 20:53:08

标签: javascript node.js express encryption multer

目前,我正在使用 multer 库来保存文件系统上的文件。此应用程序使用节点 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,
        });
    });
});

我尝试使用加密库来加密文件,但它无法正常工作。我认为 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'));

1 个答案:

答案 0 :(得分:0)

你能试试吗

app.post('/upload', function(req, res) {
    upload(req, res, function(err) {
        var fileName = req.file.destination +"\\"+ req.file.filename
        var input = fs.createReadStream(fileName);
        var output = fs.createWriteStream(fileName + ".enc");
        input.pipe(cipher).pipe(output);
        output.on('finish', function() {
            fs.unlink(fileName, (err) => {
                if (err) throw err;
                console.log('Encrypted  file written to disk!');
                res.end('Encrypted  file written to disk!')
            });

        });
    })
})