Image file cut off when uploading to AWS S3 bucket

2019-07-24 07:53发布

问题:

When I upload a larger image (3+ MB) to an AWS S3 bucket, only part of the image is being being saved to the bucket (about the top 10% of the image, the rest displaying as grey space). These images consistently show 256 KB size. There isn't any issue with smaller files.

Here's my code:

s3 = boto3.resource('s3') s3.Bucket(settings.AWS_MEDIA_BUCKET_NAME).put_object(Key=fname, Body=data)

...where data is binary data of image file.

No issues when files are smaller size, and in the S3 bucket the larger files all show as 256 KB.

I haven't been able to find any documentation about why this might be happening. Can someone please point out what I'm missing?

Thanks!

回答1:

I had the same issue and it took me hours to figure it out. I finally fixed it by creating a stream. This is my code:

const uploadFile = (filePath) => {
  let fileName = filePath;
  fs.readFile(fileName, (err, data) => {

  let body= fs.createReadStream(filePath);

   if (err) throw err;
   const params = {
      Bucket: 'bucketname', // pass your bucket name
      Key: fileName; 
      Body: body,
      ContentType: 'image/jpeg',
      ContentEncoding: 'base64',
   };
   s3.upload(params, function(s3Err, data) {
       if (s3Err) throw s3Err;
       console.log(`File uploaded successfully at ${data.Location}`);
       });
    });
};