Created
October 14, 2020 12:47
-
-
Save crrmacarse/1d62425ede0790997e5e5917805bb609 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as AWS from 'aws-sdk' | |
import Env from '@ioc:Adonis/Core/Env' | |
import { v4 as uuid } from 'uuid' | |
import { ManagedUpload } from 'aws-sdk/clients/s3' | |
const AWS_BUCKET_NAME = Env.getOrFail('AWS_BUCKET_NAME') as string | |
const AWS_REGION = Env.getOrFail('AWS_REGION') as string | |
const AWS_SECRET_ACCESS_KEY = Env.getOrFail('AWS_SECRET_ACCESS_KEY') as string | |
const AWS_ACCESS_KEY_ID = Env.getOrFail('AWS_ACCESS_KEY_ID') as string | |
const s3 = new AWS.S3({ | |
region: AWS_REGION, | |
secretAccessKey: AWS_SECRET_ACCESS_KEY, | |
accessKeyId: AWS_ACCESS_KEY_ID, | |
}) | |
export const uploadToS3Bucket = async (file: any) => { | |
const contentType = file.headers['content-type'] | |
const subType = contentType.slice(contentType.lastIndexOf('/') + 1) | |
const fileName = uuid() + '.' + subType | |
const s3Params = { | |
Bucket: AWS_BUCKET_NAME, | |
Key: fileName, | |
Body: file, | |
ContentType: contentType, | |
ACL: 'public-read', | |
} | |
return await new Promise((resolve: (value:string) => void, reject) => { | |
s3.upload(s3Params, (err: Error, data: ManagedUpload.SendData) => { | |
if (err) { | |
reject(err) | |
} | |
resolve(data.Location) | |
}) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment