簡體   English   中英

使用 Node.js 將圖像上傳到 Amazon S3 會產生一個小的透明方塊

[英]Uploading image to Amazon S3 with Node.js results in a small transparent square

我正在將圖像上傳到 Amazon S3 存儲桶,但是當它到達那里時,它是一個小的透明方塊,將來我將使用前端應用程序,文件將從用戶計算機上傳。

我正在使用 ReGex 轉換為 base64,但是當它到達 S3 Bucket 時,它是一個小方塊,如下所示:

https://s3.amazonaws.com/node-str-img-bucket/v0u2HHYolOYwXprSeU73v.jpg

我用於測試上傳的原始文件 URL 您可以點擊此處查看

這是我的 JavaScript 上傳過程:

AWS.config.update(config.AWS);
const s3 = new AWS.S3();
const bucket = 'node-str-img-bucket';

let filename = nanoid().toString() + '.jpg';
let rawdata = req.body.image;
let matches = rawdata.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/);
let type = matches[1];
let buffer = new Buffer(matches[2], 'base64');

let params = {
    Bucket: bucket,
    Key: filename,
    Body: rawdata,
    ContentType: type,
    ACL: 'public-read'
};

await s3.upload(params, (error, data) => {
    if (error) {
        console.log(error);
    } else {
        console.log(data);
    }
});

任何你能幫助我的東西都會很好。

使用putObject而不是upload

await s3.putObject(params, (error, data) => {
  if (error) {
    console.log(error);
  } else {
    console.log(data);
  }
});

還將contentTypeEncoding更改為:

let params = {
  Bucket: bucket,
  Key: filename,
  Body: rawdata,
  ContentEncoding: 'base64',
  ContentType: 'image/jpeg'
  ACL: 'public-read'
};

有同樣的問題,並試圖解決它幾個小時。 似乎問題來自 API 網關配置。 如果您使用的是控制台,請轉到設置並添加到Binary Media Types */* or using open api add x-amazon-apigateway-binary-media-types: [ " / " ]` 在文件的頂部

req.files[0] 將有以下數據

{ fieldname: 'img', originalname: 'Annotation 2021-01-11 095535.png', encoding: '7bit', mimetype: 'image/png', buffer: <Buffer 89 50 4e 47 0d 0a 1a 0a 00 00 00 0D 49 48 44 52 00 00 06 2D 00 00 01 A2 08 06 00 00 00 9B 85 3E 60 00 00 00 01 73 52 47 42 00 AE CE 1C E9 00 00 00 04 ... 38012多個字節>,大小:38062 }

現在試試這個 -

const { originalname, buffer, encoding, mimetype } = req.files[0]
s3.upload ({Bucket: 'somebucket',
        Key: originalname, 
        Body: buffer,
        ContentEncoding: encoding,
        ContentType: mimetype,
    },function (err, data) {
    if (err) {
       console.log("Error", err);
     } if (data) {
       console.log("Upload Success", data.Location);
     }
   })

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM