在将文件上传到 s3 存储桶之前如何使用 multer 重命名文件?
How to rename a file with multer before uploading it to s3 bucket?
我想使用 multer
、node.js
和 express.js
重命名每个文件,然后再将其上传到 aws s3 存储桶
这是我当前的实现方式
字体结束
const file = e.target.files[0];
const formData = new FormData();
formData.append('file', file);
const { data } = await axios.post('api/aws/upload-image', formData);
后端
var storage = multer.memoryStorage();
const upload = multer({ storage }).single('file');
const s3Client = new aws.S3({
accessKeyId: config.aws.accessKey,
secretAccessKey: config.aws.secretKey,
region: config.aws.region
});
router.post('/upload-image', async (req, res) => {
upload(req, res, function(err) {
if (err instanceof multer.MulterError || err)
return res.status(500).json(err);
const uploadParams = {
Bucket: config.aws.bucket,
Key: req.file.originalname,
ACL: 'public-read',
Body: req.file.buffer
};
s3Client.upload(uploadParams, (err, data) => {
if (err) res.status(500).json({ error: 'Error -> ' + err });
return res.status(200).send(data.Location);
});
});
});
上面的代码可以正常工作。但是我正在尝试在文件上传之前重命名该文件。
我想到了这样做:
var storage = multer.diskStorage({
filename: function (req, file, cb) {
cb(null, Date.now() + '-' +file.originalname )
}
})
但是 returns 是文件元素,而不是 blob 元素,因此不会上传到 s3 存储桶。
我怎样才能做到当文件被发送到 node.js 时,我首先更改文件名,然后上传文件?
upload
方法使用了PutObjectRequest
,PutObjectRequest构造函数关键参数实际上是上传文件的名称。
只需将 Key
值更改为您的新名称。
const uploadParams = {
Bucket: config.aws.bucket,
Key: "NEW_NAME_WHAT_YOU_WANT", // req.file.originalname,
ACL: 'public-read',
Body: req.file.buffer
};
我想使用 multer
、node.js
和 express.js
这是我当前的实现方式
字体结束
const file = e.target.files[0];
const formData = new FormData();
formData.append('file', file);
const { data } = await axios.post('api/aws/upload-image', formData);
后端
var storage = multer.memoryStorage();
const upload = multer({ storage }).single('file');
const s3Client = new aws.S3({
accessKeyId: config.aws.accessKey,
secretAccessKey: config.aws.secretKey,
region: config.aws.region
});
router.post('/upload-image', async (req, res) => {
upload(req, res, function(err) {
if (err instanceof multer.MulterError || err)
return res.status(500).json(err);
const uploadParams = {
Bucket: config.aws.bucket,
Key: req.file.originalname,
ACL: 'public-read',
Body: req.file.buffer
};
s3Client.upload(uploadParams, (err, data) => {
if (err) res.status(500).json({ error: 'Error -> ' + err });
return res.status(200).send(data.Location);
});
});
});
上面的代码可以正常工作。但是我正在尝试在文件上传之前重命名该文件。
我想到了这样做:
var storage = multer.diskStorage({
filename: function (req, file, cb) {
cb(null, Date.now() + '-' +file.originalname )
}
})
但是 returns 是文件元素,而不是 blob 元素,因此不会上传到 s3 存储桶。
我怎样才能做到当文件被发送到 node.js 时,我首先更改文件名,然后上传文件?
upload
方法使用了PutObjectRequest
,PutObjectRequest构造函数关键参数实际上是上传文件的名称。
只需将 Key
值更改为您的新名称。
const uploadParams = {
Bucket: config.aws.bucket,
Key: "NEW_NAME_WHAT_YOU_WANT", // req.file.originalname,
ACL: 'public-read',
Body: req.file.buffer
};