javascript - 将调整大小的照片上传到 S3 存储桶
问题描述
我是 Nestjs 框架的初学者,尤其是打字稿。我正在研究类似 Gumtree 或 Wallapop 的东西。目前我正在将照片上传到 S3 存储桶,我的任务是上传缩略图。上传简单的照片效果很好,但我想再次上传我从前端获得的照片 ID 数组的第一张调整大小的照片。前端发布单张照片,服务器向 S3 存储桶发送单个请求,服务器将创建的 ID 和 URL 发送回前端。在提交接受整个广告的请求后,我得到了要保存在数据库中的照片 ID。我想获得照片数组的第一个 ID,下载并再次发送改变照片大小的 trought multer。我不知道如何再次将照片传递给 multer。我想强调一下,我使用的代码来自https://medium.com/@shamnad.ps/image-upload-to-aws-s3-using-nestjs-and-typescript-b32c079963e1我不明白所有代码是如何工作的。还有其他方法可以做到这一点吗?也许我的方法是错误的。
一些片段:
服务:
@Injectable()
export class FileUploadService {
constructor(
@InjectRepository(Photos)
private readonly uploadRepository: Repository<Photos>,
private readonly timerJobsService: TimerJobsService,
) {}
async uploadSingle(@Req() req, @Res() res) {
try {
await this.upload(req, res, async (error) => {
if (error) {
if (error.code === 'LIMIT_FILE_SIZE') {
return res
.status(400)
.json(`Failed to upload image file: ${error}. Max size is 2mb`);
} else {
return res
.status(400)
.json(`Failed to upload image file: ${error}`);
}
}
const photo = new Photos();
photo.url = req.files[0].location;
photo.key = req.files[0].key;
photo.to_archived = true;
await this.uploadRepository.save(photo);
this.timerJobsService.addTimeout(
photo.id,
photo.key,
1000 * 60 * 60 * 24,
);
res.status(200).json({
id: photo.id,
url: photo.url,
});
});
} catch (error) {
console.log(error);
return res.status(400).json(`Failed to upload image file: ${error}`);
}
}
async uploadSingleThumbnail(@Req() req, @Res() res) {
try {
await this.uploadThumbnail(req, res, async () => {
const photo = new Photos();
photo.url = req.files[0].location;
photo.key = req.files[0].key;
photo.to_archived = false;
await this.uploadRepository.save(photo);
res.status(200).json({
id: photo.id,
url: photo.url,
});
});
} catch (error) {
console.log(error);
return res.status(400).json(`Failed to upload image file: ${error}`);
}
}
async downloadSingle(key: string) {
try {
const properties = await s3
.getObject({
Bucket: AWS_S3_BUCKET_NAME,
Key: key,
})
.createReadStream();
const writeStream = fs.createWriteStream(
path.join(
'[path]',
key,
),
);
properties.pipe(writeStream);
} catch (e) {
console.log(e);
}
}
upload = multer({
storage: multerS3({
s3: s3,
bucket: AWS_S3_BUCKET_NAME,
acl: 'public-read',
key: function (request, file, cb) {
const file1 = file.originalname;
if (!file1.match(/\.(jpg|png|jpeg)$/)) {
cb('Wrong file format. Only _.png _.jpg _.jpeg format', true);
} else {
cb(null, `${uuid()}-${file.originalname}`);
}
},
}),
limits: { fileSize: 2097152 },
}).any();
uploadThumbnail = multer({
storage: multerS3({
s3: s3,
bucket: AWS_S3_BUCKET_NAME,
acl: 'public-read',
key: function (_, file, cb) {
cb(null, `${uuid()}-${file.originalname}-thumbnail`);
},
resize: {
width: 200,
height: 150,
},
}),
}).any();
}
控制器:
@Post()
@ApiOperation({ description: 'Upload photo' })
@ApiConsumes('multipart/form-data')
@ApiBody({
schema: {
type: 'object',
properties: {
file: {
type: 'string',
format: 'binary',
},
},
},
})
async create(@Req() request, @Res() response) {
try {
await this.fileUploadService.uploadSingle(request, response);
} catch (error) {
return response
.status(400)
.json(`Failed to upload file: ${error.message}`);
}
}
@Post()
@UseInterceptors(FileInterceptor('file'))
async createThumbnail(@UploadedFile() file, @Res() response) {
try {
await this.fileUploadService.uploadSingleThumbnail(file, response);
} catch (e) {
return response
.status(400)
.json(`Failed to upload thumbnail: ${e.message}`);
}
}
解决方案
推荐阅读
- html - div 背景颜色与其他 div 重叠,但内容不重叠
- sql - 如何在 BigQuery 中将两列聚合成数组?
- linux - 用正则表达式替换 json 文件中的 Sed
- java - 将一个节点插入到一个排序的整数链表中,这样该列表仍然与最终成员一起排序以供下一个
- php - html表单按钮重定向到同一页面
- java - 如何使用在运行时更改的动态 Cron 作业在 Weblogic 中设计 Quartz 调度程序?
- apache - rancid VIEWVC apache 重写规则,CGI 页面显示不正确
- sql - 是否有人创建了将十进制数作为参数的雪花用户定义函数 (SQL)?
- spring-boot - 无法从嵌入的 html 页面 thymeleaf-spring boot 读取会话值
- java - 如何使用 Java 和 Selenium 在 textarea 中快速设置文本