通过这些简单的几行代码,我将文件保存在服务器上。
router.post('/upload', upload.single('file'), function(req: Request, res: Response, next: Function) {
console.log(req.file);
res.json({ success: true, message: 'Uploaded' });
});
我希望在保存文件之前对其进行加密。
我有什么方法可以做到吗?
答案 0 :(得分:1)
因此,执行顺序为:
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);
});
}
}));
答案 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')
})