将图像文件上传到 s3 存储桶效果不佳。怎么修?

Uploading image file to s3 bucket doesn't work well. How to fix?

我正在使用 koa(& serverless) 设置 S3 上传功能。 我制作了 S3 上传功能,它看起来可以正常工作。但是它在 s3 存储桶中有 broken(? or empty)。 像这样。 broken image

我的节点项目正在使用 koa 和无服务器(桶设置已在此处完成)。

这是我的package.json

{
// ...

  "dependencies": {
    "aws-sdk": "^2.464.0",
    "dotenv": "^8.0.0",
    "joi": "^14.3.1",
    "koa": "^2.7.0",
    "koa-body": "^4.1.0",
    "koa-router": "^7.4.0",
    "promise-mysql": "^3.3.2",
    "serverless-http": "^2.0.2",
    "serverless-offline": "^4.10.6"
  },

// ...
}

这是我的 app.js

const Koa = require('koa');
const koaBody = require('koa-body');
const routes = require('./api/index');


const app = new Koa();
app.use(koaBody({ multipart: true }));
app.use(routes.routes()).use(routes.allowedMethods());

app.use(ctx => {
    ctx.body = 'hello world';
});
module.exports = app;

这是我的路由器

const Router = require('koa-router');
const auth = new Router();

const AWS = require('aws-sdk');
const S3 = new AWS.S3();
const fs = require('fs');

const BUCKET = 'chacha-s3-test';

auth.post('/image-up', async(ctx)=> {
    const image = ctx.request.files.image;

    const {
        name, path, type
    } = image

    console.log('name :', name); //world.png
    console.log('path :', path); //C:\<my local path>\upload_d7ac6297fa2d0fb09495695f1536a41a
    console.log('type :', type); //image/png

    const { key, url } = await putS3Object(
        name,
        path,
        type,
    ).then(()=> getSignedUrl(name));
    ctx.body = {key, url} // {}, no return..
})

function putS3Object(key, path, type) {
    const stream = fs.createReadStream(path);

    return S3.putObject({
        Body: stream,
        Bucket: BUCKET,
        ContentType: type,
        Key: key
    }).promise();
}

function getSignedUrl(key) {
    const params = {Bucket:BUCKET, Key: key};
    return S3.getSignedUrl('getObject', params);
}

module.exports = auth;

此代码可以上传文件。但是 s3 中的图像已损坏。它不 return url。

图像文件来自 React FormData e.target.files[0] 我需要写react代码吗?


我希望 s3 存储桶中上传的图像文件显示原件(世界地图图片)。但它只是小方块和黑色背景(虽然大小几乎相同(257.9KB))。broken image

没有错误信息。并且图像文件已成功上传。但是 s3 存储桶中的图像已损坏。

如何解决?请帮忙。

谢谢。祝你有美好的一天!

您应该使用 upload() 方法而不是 putObject(),因为 upload() 方法将接受没有定义 content-length 的流,而 putObject()才不是。这是我目前的使用方式:

const S3Client = new AWS.S3({apiVersion: '2006-03-01'});
const fs = require('fs');

const upload = (bucket, key, readable) => {
    const params = {Bucket: bucket, Key: key, Body: readable};
    return S3Client.upload(params).promise();
};

(async () => {
   try {
    const readable = fs.createReadStream(some path here...);
    const uploaded = upload(config.destination.bucket, config.destination.key, readable);
    // Further stuff goes here....
   } catch(e) {
    console.log('Error happend while uploading: ', e.message)
   }
})();

更多关于upload()方法,您可以阅读here

希望对您有所帮助。