0

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

committer
  • 129
  • 1
  • 12
  • Have you tried `await sharp(Buffer.from(response.body))`? – jarmod Oct 23 '21 at 18:02
  • I'm getting `Input buffer contains unsupported image format` when trying it on png and jpg images. – committer Oct 23 '21 at 18:06
  • Not very familiar with the `got` library, but it seems to require the body to be resolved asynchronously, for example: `const body = await got(url).buffer()` which essentially sets responseType: buffer and resolveBodyOnly: true. – jarmod Oct 23 '21 at 18:57
  • I get `got(...).buffer is not a function` when I do that, not sure why. It should work, based on this example I found: https://stackoverflow.com/a/63965189/10014988 – committer Oct 23 '21 at 19:15

1 Answers1

3

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.

jarmod
  • 71,565
  • 16
  • 115
  • 122
  • It looks like I had to force a never major version of `got` to be installed, even though I installed it quite recently. – committer Oct 23 '21 at 21:14