NodeJS-KOA:上传到 S3 的图像已损坏

时间:2021-07-09 08:33:51

标签: node.js amazon-s3 koa

我正在将图像上传到 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);

0 个答案:

没有答案