如何使用 express multer 加密文件

How to encrypt file using express multer

通过这些简单的几行代码,我将文件保存在服务器上。

router.post('/upload',  upload.single('file'), function(req: Request, res: Response, next: Function) {
    console.log(req.file);
    res.json({ success: true, message: 'Uploaded' });
});

我想在保存文件之前加密文件。

有什么办法可以做到吗?

  • Multer 提供了丰富的事件集,可以为您提供更好的服务
    控制您的文件上传。

因此,执行顺序为:

  1. onParseStart
  2. onFileUploadStart/onFileUploadData...
  3. onFileUploadComplete
  4. onParseEnd

因此,在您的情况下,您的加密过程应该在 onFileUploadComplete 中,方法如下:

    var fs = require('fs');       
    var encryptor = require('file-encryptor');
    var key = 'My Super Secret Key';          
    app.use(multer({      
            onFileUploadComplete: function (file) {
                 console.log(file.fieldname + ' uploaded to  ' + file.path);
             // Encrypt file.
               encryptor.encryptFile(file, 'encryptedFile.dat', key, function(err) {
                  // Encryption complete.remove original file
                   fs.unlink(file);
                         });
                       }
                   }));

加密文件的一种方法是使用 multer 的缓冲区 memoryStorage() 和 Node.js 内置 crypto library.

import multer from 'multer'
import { scryptSync, createCipheriv } from 'crypto'
import { mkdirSync, existsSync, writeFileSync } from 'fs'

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

const encrypt = (buffer) => {
  // More info: https://nodejs.org/api/crypto.html
  const algorithm = 'aes-192-cbc'
  const iv = Buffer.alloc(16, 0)
  const key = scryptSync('super strong password', 'salt', 24)

  const cipher = createCipheriv(algorithm, key, iv)
  return Buffer.concat([cipher.update(buffer), cipher.final()])
}

const saveEncryptedFile = (buffer, filePath) => {
  if (!existsSync(path.dirname(filePath))) {
    mkdirSync(path.dirname(filePath))
  }
  writeFileSync(filePath, encrypt(buffer))
}

router.post('/upload', upload.single('file'), ({ file }, res, next) => {
  saveEncryptedFile(file.buffer, './your-file-path')
})