Skip to content

Instantly share code, notes, and snippets.

@crrmacarse
Created October 14, 2020 12:47
Show Gist options
  • Save crrmacarse/1d62425ede0790997e5e5917805bb609 to your computer and use it in GitHub Desktop.
Save crrmacarse/1d62425ede0790997e5e5917805bb609 to your computer and use it in GitHub Desktop.
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