Home > OS >  Resize and compress image from URL and upload to S3
Resize and compress image from URL and upload to S3

Time:10-24

I have a function that is supposed to get an image from an external URL, optimize it with sharp, and then upload the image to S3.

But it doesn't seem like I can get sharp to work for resizing and compression.

Here is my current code:

const got = require('got');
const sharp = require('sharp');
const AWS = require('aws-sdk');

const s3 = new AWS.S3({
  credentials,
});

async function uploadFile(url) {
  // Get file
  const response = await got(url, { responseType: 'buffer' });

  // Resize, compress and convert image before upload
  const { data, info } = await sharp(response.body)
    .resize({ width: 512 })
    .jpeg({ quality: 70 })
    .toBuffer();

  console.log('data:', data);

  const uploadedFile = await s3
    .upload({
      Bucket: bucket,
      Key: 'filename.jpg',
      Body: data,
      ContentType: 'image/jpeg',
    })
    .promise();

  console.log('uploadedFile:', uploadedFile);
}

Error I get: Input file is missing

The code fails when the sharp method is called.

The kind of output I get from response.body link

CodePudding user response:

I think you need to make two changes, as follows:

const body = await got(url).buffer();

and:

const data = await sharp(body)
    .resize({ width: 512 })
    .jpeg({ quality: 70 })
    .toBuffer();

With those changes, your code works for me. I downloaded a random image from the web and uploaded it successfully to S3. Also, make sure you have up to date packages for got and sharp.

  • Related