如何使用快速multer加密文件

时间:2016-02-17 06:41:31

标签: node.js 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' });
});

我希望在保存文件之前对其进行加密。

我有什么方法可以做到吗?

2 个答案:

答案 0 :(得分:1)

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

因此,执行顺序为:

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

  5. 因此,在您的情况下,您的加密过程应该在 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);
                             });
                           }
                       }));
    

答案 1 :(得分:1)

加密文件的一种方法是使用 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')
})