I've found a way to do this with aws-sdk, this code is not 100% mine:
uploadToS3Bucket
function:
import * as AWS from "aws-sdk";
import { v4 as uuid } from "uuid";
const s3 = new AWS.S3({
region: process.env.AWS_REGION,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
});
export const uploadToS3Bucket = async (
file: any,
bucket: string
): Promise<{ key: string; url: string }> => {
try {
const { type, subtype, extname } = file;
let mimeType = type + "/" + subtype;
let fileType = "image/jpg";
const name = uuid() + "." + extname;
let buffer = Buffer.from(JSON.stringify(file), "utf-8");
await s3
.putObject({
Key: name,
Bucket: bucket,
ContentType: fileType,
Body: buffer.toString("base64"),
ACL: "public-read",
})
.promise();
let url = `https://${bucket}.s3.amazonaws.com/${name}`;
console.log(url);
return {
key: name,
url,
};
} catch (err) {
console.log(err);
return err;
}
};
And in the controller:
public async store({ request }: HttpContextContract) {
let file = getFileFromRequest(request, "defined_file_prop_name_here");
if (file) {
await uploadToS3Bucket(file, BUCKET_NAME);
}
}