node.js - NodeJS-KOA:上传到 S3 的图像损坏
问题描述
我正在将图像上传到 S3 存储桶。这些图像正在保存,但在 S3 上下载或查看时它们已损坏。但是,代码有时似乎可以正常工作。我用来上传图片的实用功能是:
Upload(fileName, data, s3Folder) {
let randomId = crypto.randomBytes(16).toString("hex");
AWS.config.update({ region: awsConstants.S3BUCKET.Region, accessKeyId: awsConstants.S3BUCKET.AccessKeyId, secretAccessKey: awsConstants.S3BUCKET.SecretAccessKey });
var s3 = new AWS.S3();
var imageName = randomId + fileName;
//In case uploading to a specific folder
if (s3Folder) {
imageName = s3Folder + '/' + randomId + fileName
}
var params = {
Bucket: awsConstants.S3BUCKET.BucketName,
Key: imageName,
Body: data,
ContentType: mime.lookup(fileName)
};
return new Promise((resolve, reject) => {
s3.putObject(params, function (err, data) {
if (err) {
console.log('Error: ', err);
reject(new Error(err.message));
} else {
resolve({
response: data,
uploadedFileName: imageName
});
}
});
});
}
调用此实用程序的控制器代码:
async uploadImage(ctx) {
try {
var file = ctx.request.file;
if (file) {
const fileData = ctx.request.file.buffer;//Do get buffer
//const fileData = ctx.request.file.buffer.toString('binary'); tried this as well
//Utility code that uploads image
var resp = await s3Hander.Upload(file.originalname, fileData, "Profile");
if (resp && resp["response"]["ETag"]) {
ctx.status = httpConstants.HTTP_SUCCESS_OK;
ctx.body = { response: resp, S3Data: {} };
}
else {
ctx.status = httpConstants.HTTP_INTERNAL_SERVER_ERROR;
ctx.body = { response: 'Unable to upload image!' };
}
}
else {
ctx.status = httpConstants.HTTP_BAD_REQUEST;
ctx.body = { response: 'File not found!' };
}
} catch (error) {
ctx.status = httpConstants.HTTP_INTERNAL_SERVER_ERROR;
ctx.body = { response: 'Unable to upload image!' };
}
}
我很确定我存储在 S3 上的数据存在一些问题,因为也无法从 AWS 控制台从存储桶中查看它。这里有什么问题吗?我正在使用 KOA 作为中间件
const multer = require('@koa/multer');
const upload = multer();
路由器:
applicationRouterManager.post('/uploadImage', upload.single('avatar'), ProfileController.uploadImage);
解决方案
推荐阅读
- flutter - 如何在 Flutter 中进行芯片按键设计
- css - 设置根字体大小不影响 Safari 中的边距、填充等 rem 单位
- javascript - 如何在 JavaScript 中访问函数调用上下文?
- c# - 有什么方法可以让 C# 编译器在编译时检查更多?
- javascript - 有自定义图表的方法吗?
- javascript - React Hooks - 使用 prevState 时防止重新渲染
- c# - 文本文件编写器和阅读器不适用于我的 WPF
- django - 为什么 django 模型错误不断引发错误?
- angular - 加载微调器确实显示,即使它的真实状态是角度的
- r - 在 R 中更改 libpath 不生效