I’m trying to upload an image by camera to AWS3 but I have found only tutorials about file transfer.
I read that file transfer is now deprecated, how could I solve this problem ?
This is my code but I’m getting 403 fobidden error:
const BUCKET_NAME = 'xxxxxxxxxxx';
const IAM_USER_KEY = 'xxxxxxxxxxx';
const IAM_USER_SECRET = 'xxxxxxxxxxxx';
let bucket = new AWS.S3(
{
accessKeyId: IAM_USER_KEY,
secretAccessKey: IAM_USER_SECRET,
region: "eu-central-1"
}
);
const params = {
Bucket: "etproject",
Key: "one/smile.jpg",
Body: "/assets/imgs/test_images/smile.jpg",
ContentType: "image/jpeg",
ACL: 'public-read'
};
bucket.upload(params, function (err, data) {
console.log("err", err);
console.log("data", data);
if (err) {
console.log('There was an error uploading your file: ', err);
return false;
}
console.log('Successfully uploaded file.', data);
return data;
});
It’s the third topics I ask and I not receive an aswer or a tips. So this is my way to solve my problem. I hope I will help someone else in same condition.
I first follow this guide online to set amazon bucket for IAM users: https://www.youtube.com/watch?v=Oc69SEtbM_U
I found that my problem was to install first the require word, and solved it by adding some code to tsconfig.json:
"types": ["node"],
"typeRoots": [
"node_modules/@types"
]
inside complireOptions. If it still does not work try to type : npm install @types/node --save -dev
and then in your page declare require like :
declare var require: any;
require('aws-sdk');
Then I configure AWS inside my costructor and create a function to upload:
let BUCKET_NAME = 'name_bucket';
const IAM_USER_KEY = 'xxxxxxxxxxxx';
const IAM_USER_SECRET = 'xxxxxxxxxxxxxxxx';
AWS.config = new AWS.Config();
AWS.config.accessKeyId = IAM_USER_KEY;
AWS.config.secretAccessKey = IAM_USER_SECRET;
AWS.config.region = "region";
This is my function:
let date = new Date();
let current_seconds = date.getSeconds();
var bufferValue = this.dataURItoBlob(file);
let bucket = new AWS.S3();
bucket.createBucket(function () {
var params = {
Bucket: 'xxxxxxx',
Key: 'name'+current_seconds+'.png',
Body: bufferValue ,
ContentType: 'image/png',
ACL: 'public-read'
};
bucket.upload(params, function (err, data) {
if (err) {
console.log('error in callback');
console.log(err);
}
console.log('success');
console.log(data);
});
});
BufferValue is the image base64 in blob passed by camera to dataURItoBlob function.
I hope I was clear.
If you use the new amplify api from AWS, it is a lot cleaner and they handle the configuration for you.
https://aws-amplify.github.io/amplify-js/media/storage_guide.html
async saveFile(_event) {
console.log(_event);
const files = _event.detail.target.files;
const key = `${new Date().getTime()}:${files[0].name}`;
Storage.put(key, files[0], {
contentType: files[0].type,
level: "private"
})
.then(result => console.log(result))
.catch(err => console.log(err));
}
My AWS Amplify project is here.