Created
May 17, 2023 16:40
-
-
Save evzpav/1946efed84ad9da35884d423d0e85f34 to your computer and use it in GitHub Desktop.
NestJS AWS s3 upload
This file contains 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 { Injectable } from '@nestjs/common'; | |
import { configService } from '../enviroment.config'; | |
import * as AWS from 'aws-sdk'; | |
import { S3 } from 'aws-sdk'; | |
@Injectable() | |
export class AwsService { | |
s3: AWS.S3; | |
constructor() { | |
this.s3 = new AWS.S3({ | |
accessKeyId: configService.getS3Config().AWS_ACCESS_KEY_ID, | |
secretAccessKey: configService.getS3Config().AWS_SECRET_ACCESS_KEY, | |
}); | |
} | |
public getFileName(file: any): string { | |
return `${file.originalname}`; | |
} | |
public getUrl(file: any, filename, path): string { | |
return `${configService.getS3Config().AWS_ENDPOINT_URL}/${path}${filename}`; | |
} | |
public async uploadFile( | |
file: any, | |
path?: string, | |
contentType?: string, | |
): Promise<string> { | |
const fileName = this.getFileName(file); | |
const params: S3.Types.PutObjectRequest = { | |
ACL: 'public-read', | |
Body: file.buffer, | |
Bucket: configService.getS3Config().BUCKET, | |
Key: path + fileName, | |
ContentType: contentType || 'application/pdf', | |
}; | |
const data = await this.s3 | |
.putObject(params) | |
.promise() | |
.then( | |
(item) => { | |
console.log(item); | |
return this.getUrl(file, fileName, path); | |
}, | |
(err) => { | |
console.log(err); | |
return err; | |
}, | |
); | |
return data; | |
} | |
public async getObject(url): Promise<Buffer> { | |
const fileName = this.getFilePathFromUrl(url); | |
console.log(fileName); | |
const params = { | |
Bucket: configService.getS3Config().BUCKET, | |
Key: fileName, | |
}; | |
const data = await this.s3 | |
.getObject(params) | |
.promise() | |
.then( | |
(item) => { | |
console.log(item); | |
return item.Body; | |
}, | |
(err) => { | |
console.log(err); | |
return err; | |
}, | |
); | |
return data; | |
} | |
private getFilePathFromUrl(myUrl) { | |
let url = new URL(myUrl); | |
return url.pathname.substring(1, url.pathname.length); | |
} | |
} |
This file contains 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
public getS3Config() { | |
return { | |
BUCKET: process.env.AWS_S3_BUCKET_NAME, | |
AWS_ACCESS_KEY_ID: process.env.AWS_ACCESS_KEY_ID, | |
AWS_SECRET_ACCESS_KEY: process.env.AWS_SECRET_ACCESS_KEY, | |
AWS_ENDPOINT_URL: process.env.AWS_ENDPOINT_URL, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment