【发布时间】:2021-04-15 21:12:42
【问题描述】:
您好,我需要在 s3 上一次上传多张图片。
目前我正在使用express-fileupload 在 AWS 上上传单个图像,我想使用相同的方法将多个文件上传到 s3 并使用 mongodb 上的 url 更新图像数组。
我的架构属性:
const ServiceSchema = new mongoose.Schema(
{
photo: [
{
type: String,
default: 'no-photo.jpg',
},
],
});
module.exports = mongoose.model('Service', ServiceSchema);
我的控制器:
// @desc Upload photo for service
// @route PUT /api/v1/services/:id/photo
// @access Private
exports.servicePhotoUpload = asyncHandler(async (req, res, next) => {
const service = await Service.findById(req.params.id);
if (!service) {
return next(new ErrorResponse(`Service not found with id of ${req.params.id}`, 404));
}
// Make sure user adding service is business owner
if (service.user.toString() !== req.user.id && req.user.role !== 'admin') {
return next(
new ErrorResponse(
`User ${req.user.id} is not authorized to update this service to business ${service._id}`,
401
)
);
}
// File Upload validation
if (!req.files) {
return next(new ErrorResponse(`Please upload a file.`, 400));
}
const file = req.files.file;
// Make sure it is a valid image file
if (!file.mimetype.startsWith('image')) {
return next(new ErrorResponse(`Please upload a valid image file.`, 400));
}
//Check File Size
if (file.size > process.env.MAX_FILE_UPLOAD) {
return next(
new ErrorResponse(
`Please upload an image less then ${process.env.MAX_FILE_UPLOAD / 1024}KB in size.`,
400
)
);
}
// Create custom filename
file.name = `service-uploads/servicePhoto_${service._id}${path.parse(file.name).ext}`;
uploadToS3({
fileData: req.files.file.data,
fileName: file.name,
})
.then(async (result) => {
console.log('Success Result: ', result);
await Service.findByIdAndUpdate(service._id, { photo: result.Location });
return res
.status(200)
.json({ success: true, message: 'Service photo added successfully', url: result.Location });
})
.catch((err) => {
console.log(err);
return next(new ErrorResponse('Failed to upload file to S3', 500));
});
});
我的实用程序文件将文件上传到 S3:
const AWS = require('aws-sdk');
const uploadToS3 = (options) => {
// Set the AWS Configuration
AWS.config.update({
accessKeyId: process.env.AWS_S3_ACCESS_KEY,
secretAccessKey: process.env.AWS_S3_SECRET_KEY,
region: 'us-east-2',
});
// Create S3 service object
const s3 = new AWS.S3({ apiVersion: '2006-03-01' });
// Setting up S3 upload parameters
const params = {
Bucket: 'toolbox-uploads',
Key: options.fileName, // File name you want to save as in S3
Body: options.fileData, //
};
// Return S3 uploading function as a promise so return url can be handled properly
return s3.upload(params).promise();
};
module.exports = uploadToS3;
我的路由器:
const express = require('express');
const {
servicePhotoUpload
} = require('../controllers/service');
const Service = require('../models/Service');
router.route('/:id/photo').put(protect, authorize('publisher', 'business', 'admin'), servicePhotoUpload);
module.exports = router;
以上代码 100% 工作。
我有点困惑,因为有不同的方法,谷歌和堆栈溢出都没有对我有用,而且它们都没有获取返回 url 并保存到数据库中。
我想制作单独的实用程序文件以将多个文件上传到 3,就像我为单个文件所做的那样,以便在任何地方使用它们。该文件应返回上传的网址,以便我可以更新我的数据库。 我已经尝试过 multer-s3,但没有适合我的解决方案。
【问题讨论】:
-
link 看看这是我几天前帮助解决的非常相似的情况
-
@Erykj97 谢谢,但是如何将上传的文件 url 保存到数据库中?
-
我在那里为您发布了一个答案,以便其格式整齐@Arslan Ameer
标签: node.js mongodb express amazon-s3 mongoose