首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >将本地文件夹中的图像上传到S3

将本地文件夹中的图像上传到S3
EN

Stack Overflow用户
提问于 2018-05-29 07:00:00
回答 1查看 1.2K关注 0票数 2

在我的应用程序中,我将图像上传到本地/tmp文件夹并进行一些转换。图片被正确地保存在那里。之后,我想将此图像上传到S3存储桶中,但到目前为止,我只能设法生成空白图片。

这是我的代码:

//Pick the local image and make it binary
var fs = require('fs');
var bufferedData = '';
fs.readFile(imagePath, function (err, data) {
   if (err) { throw err; }
   bufferedData = new Buffer(data, 'binary');
}


//Send data to s3    
const uploadToS3 = async (idKey: string, modifiers: string, bufferedData) => {
  try {
    return await S3.upload({
      Bucket: 'mirage-thumbnails',
      Key: `${process.env.APP_ENV}/${idKey}/${modifiers}`,
      Body: bufferedData,
      ContentType: 'image/png',
      ACL: 'public-read',
      CacheControl: 'max-age=0',
    }).promise();
  } catch (e) {
    console.error(e.message, e);
  }
};
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-05-29 07:03:03

但是,除了使用readFile,您还可以向s3.upload提供一个readable stream,这将允许您在不耗尽内存的情况下上传大文件,并使代码更容易一些。

S3.upload({
    Bucket: 'mirage-thumbnails',
    Key: `${process.env.APP_ENV}/${idKey}/${modifiers}`,
    Body: fs.createReadStream(imagePath),
    ContentType: 'image/png',
    ACL: 'public-read',
    CacheControl: 'max-age=0',
}).promise();

在您的代码中,调用uploadToS3时不会填充bufferedData。您应该等待文件被读取,然后调用uploadToS3。代码应如下所示:

const fs = require('fs');
const promisify = require('util').promisify;

// Promisify readFile, to make code cleaner and easier.
const readFile = promisify(fs.readFile);

const uploadToS3 = async(idKey, modifiers, data) => {
  return S3.upload({
    Bucket: 'mirage-thumbnails',
    Key: `${process.env.APP_ENV}/${idKey}/${modifiers}`,
    Body: data,
    ContentType: 'image/png',
    ACL: 'public-read',
    CacheControl: 'max-age=0',
  }).promise();
};

const uploadImage = async(path) => {
  const data = await readFile(imagePath);
  // Wait until the file is read
  return uploadToS3('key', 'modifier', data);
};

uploadImage('./some/path/image.png')
  .then(() => console.log('uploaded!'))
  .catch(err => console.error(err));

使用streams,只需将uploadImage更改为:

const uploadImage = async(path) => {
      const stream = fs.createReadStream(path);
      return uploadToS3('key', 'modifier', stream);
};
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50574303

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档