How to encrypt file using express multer

2019-09-17 06:56发布

By having these simple few lines of code I've got file saved on server.

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

I want to encrypt the file before it is get saved.

Is there any way I can do that?

1条回答
你好瞎i
2楼-- · 2019-09-17 07:33
  • Multer provides a rich set of events which can give you better
    control over your file uploads.

Therefore, the order of execution is:

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

So,in your case your encrypting proccess should be in onFileUploadComplete by doing something like this:

    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);
                         });
                       }
                   }));
查看更多
登录 后发表回答