[英]How to read and upload image to AWS S3 with Nodejs
I have put together upload.js
script that reads the image jpg file from a local drive and uploads it to AWS S3 bucket.我已经将
upload.js
脚本放在一起, upload.js
脚本从本地驱动器读取图像 jpg 文件并将其上传到 AWS S3 存储桶。
var fs = require('fs');
var AWS = require('aws-sdk');
AWS.config.update({region: 'us-east-1'});
const BUCKET_NAME = 'my-bucket-name';
let filepath = '/home/user/test-image.jpeg';
const content = fs.readFileSync(filepath, {encoding: 'base64'});
let params = {
params: {
Bucket: BUCKET_NAME,
Key: 'test.jpeg',
Body: content
}
};
var upload = new AWS.S3.ManagedUpload(params);
var promise = upload.promise();
promise.then(
function(data) {
console.log("Successfully uploaded photo.");
},
function(err) {
console.error("There was an error uploading: ", err.message);
}
);
When I run it with node upload.js
the image is uploaded.当我使用
node upload.js
运行它时,图像被上传。 But when I donwload it back the downloaded image is corrupted and cannot be opened with image viewer.但是当我将其下载回来时,下载的图像已损坏,无法使用图像查看器打开。 What am I doing wrong?
我究竟做错了什么?
Add the ContentType: image/jpeg
to your params
object and Loose the base64 encoding
, this configuration will work for you as well.将
ContentType: image/jpeg
添加到您的params
对象并松开base64 encoding
,此配置也适用于您。
var fs = require('fs'); const AWS = require('aws-sdk'); // const s3 = new AWS.S3(); AWS.config.update({ region: 'us-east-1' }); const mime = require('mime'); const BUCKET_NAME = 'my-bucket-name'; let filepath = '/home/user/test-image.jpeg'; const content = fs.readFileSync(filepath); console.log(mime.getType(filepath)); let params = { params: { Bucket: BUCKET_NAME, Key: 'cancel.jpeg', Body: content, ContentType: mime.getType(filepath), }, }; var upload = new AWS.S3.ManagedUpload(params); var promise = upload.promise(); promise.then( function (data) { console.log('Successfully uploaded photo.'); }, function (err) { console.error('There was an error uploading: ', err.message); } );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.