Skip to content

Instantly share code, notes, and snippets.

@jedsmith13
Created June 25, 2019 15:50
Show Gist options
  • Save jedsmith13/0c7135ac19af193b893057cf9784550f to your computer and use it in GitHub Desktop.
Save jedsmith13/0c7135ac19af193b893057cf9784550f to your computer and use it in GitHub Desktop.
Uploading files using NestJS
// File Upload Controller
@Post(':id/upload-image')
@UseGuards(CustomAuthGuard)
@UseInterceptors(FilesInterceptor('files'))
public async uploadActivityImage(
@Param() params: any,
@UploadedFiles() files: any,
@Body() data: any,
): Promise<{
itemId: number;
photos: IPhoto[];
}> {
if (files && Array.isArray(files)) {
const uploadPromises = files.map(async (file, index: number) => {
const fileUrl = await this.s3UploadsService.uploadImage(file, id);
// Save fileUrl to database
});
const photos = await Promise.all(uploadPromises);
return {
id: params.id,
photos,
};
}
}
// File Upload Service
import { Injectable } from '@nestjs/common';
import * as AWS from 'aws-sdk';
import { v4 as uuid } from 'uuid';
@Injectable()
export class S3UploadsService {
public AWS_S3_BUCKET_NAME: string = process.env.AWS_S3_BUCKET_NAME;
public s3: AWS.S3 = new AWS.S3({ apiVersion: '2006-03-01' });
constructor() {
AWS.config.update({
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
});
}
/**
* Upload a file to S3 that is for an item.
*
* @param file
* @param activityId
*/
public uploadImage(file: any, itemId: number): Promise<string> {
return this.uploadImage(
file,
`item/${itemId}/${uuid()}`,
'item',
);
}
}
@danipralea
Copy link

very nice. thank you. just a note on aws credentials: https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/loading-node-credentials-shared.html
I'm giving this, cause I had a lot of reports from Github Helper Bot with exposing credentials 😄

@phvictorino
Copy link

You saved my life! Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment