Skip to content

Commit

Permalink
Add file upload functionality using multer and AWS S3
Browse files Browse the repository at this point in the history
  • Loading branch information
JHM69 committed Feb 23, 2024
1 parent b5a9adf commit c4d05df
Show file tree
Hide file tree
Showing 7 changed files with 1,943 additions and 82 deletions.
8 changes: 1 addition & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,8 @@ Implementing Shuno-Backend with express js using Postgres Database and prisma.
npm install
```

### Start PostgreSQL in Windows

```
pg_ctl.exe start -D "C:\Program Files\PostgreSQL\16\data"
```


### Connect the created server

create a _.env_ file at the root of the project
populate it with the url of your database

Expand Down
1,930 changes: 1,857 additions & 73 deletions package-lock.json

Large diffs are not rendered by default.

10 changes: 8 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,20 +22,24 @@
"keywords": [
"music",
"audio",
"spotify"
"spotify"
],
"author": {
"name": "Jahangir",
"email": "[email protected]"
},
"dependencies": {
"@prisma/client": "^5.6.0",
"@aws-sdk/client-s3": "^3.515.0",
"@prisma/client": "^5.6.0",
"aws-sdk": "^2.1564.0",
"bcryptjs": "^2.4.3",
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"express": "^4.17.1",
"express-jwt": "^6.1.0",
"jsonwebtoken": "^8.5.1",
"multer": "^1.4.5-lts.1",
"multer-s3": "^3.0.1",
"slugify": "^1.6.0"
},
"devDependencies": {
Expand All @@ -45,6 +49,8 @@
"@types/express": "^4.17.13",
"@types/express-rate-limit": "^5.1.3",
"@types/jsonwebtoken": "^8.5.5",
"@types/multer": "^1.4.11",
"@types/multer-s3": "^3.0.3",
"@types/node": "^15.14.9",
"@typescript-eslint/eslint-plugin": "^4.31.0",
"@typescript-eslint/parser": "^4.31.0",
Expand Down
45 changes: 45 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,12 @@ import cors from 'cors';
import bodyParser from 'body-parser';
import routes from './routes/routes';
import HttpException from './models/http-exception.model';
import { upload } from './upload';
import { uploadToS3 } from './s3Upload';


const app = express();


/**
* App Configuration
Expand All @@ -17,10 +22,46 @@ app.use(routes);
// Serves images
app.use(express.static('public'));



app.post('/api/upload-image', upload.single('image'), async (req, res) => {
try {
if (!req.file) throw new Error("File is required");
const fileUrl = await uploadToS3(req.file, 'shunofiles', 'images');
res.json({ message: 'Image uploaded successfully', fileUrl });
} catch (error) {
console.log(error);
res.status(500).json({ message: error instanceof Error ? error.message : 'An error occurred' });
}
});

app.post('/api/upload-audio', upload.single('audio'), async (req, res) => {
try {
if (!req.file) throw new Error("File is required");
const fileUrl = await uploadToS3(req.file, 'shunoaudio', 'audios');
res.json({ message: 'Audio uploaded successfully', fileUrl });
} catch (error) {
console.log(error);
res.status(500).json({ message: error instanceof Error ? error.message : 'An error occurred' });
}
});



app.get('/', (req: Request, res: Response) => {
res.json({ status: 'API is running on /api' });
});












/* eslint-disable */
app.use((err: Error | HttpException, req: Request, res: Response, next: NextFunction) => {
Expand All @@ -39,6 +80,10 @@ app.use((err: Error | HttpException, req: Request, res: Response, next: NextFunc
}
});





/**
* Server activation
*/
Expand Down
10 changes: 10 additions & 0 deletions src/s3Client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// s3Client.ts
import { S3Client, S3ClientConfig } from "@aws-sdk/client-s3";

export const s3Client = new S3Client({
region: process.env.AWS_REGION,
credentials: {
accessKeyId: process.env.AWS_ACCESS_KEY_ID!,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY!
}
} as S3ClientConfig);
16 changes: 16 additions & 0 deletions src/s3Upload.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { s3Client } from './s3Client';
import { PutObjectCommand } from "@aws-sdk/client-s3";

export const uploadToS3 = async (file: Express.Multer.File, bucketName: string, keyPrefix: string): Promise<string> => {
const { originalname, buffer } = file;
const key = `${keyPrefix}/${Date.now()}-${originalname}`;

await s3Client.send(new PutObjectCommand({
Bucket: bucketName,
Key: key,
Body: buffer,
ACL: 'public-read',
}));

return `https://${bucketName}.s3.amazonaws.com/${key}`;
};
6 changes: 6 additions & 0 deletions src/upload.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// upload.ts
import multer from 'multer';

export const upload = multer({
storage: multer.memoryStorage()
});

0 comments on commit c4d05df

Please sign in to comment.