简体   繁体   English

从 URL 调整大小和压缩图像并上传到 S3

[英]Resize and compress image from URL and upload to S3

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.我有一个函数应该从外部 URL 获取图像,用sharp 优化它,然后将图像上传到 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我得到的错误: Input file is missing

The code fails when the sharp method is called.调用sharp方法时代码失败。

The kind of output I get from response.body link我从 response.body链接获得的输出类型

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.我从网上随机下载了一张图片并成功上传到 S3。 Also, make sure you have up to date packages for got and sharp.另外,请确保您拥有最新的 got 和 sharp 软件包。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM