Last active
June 25, 2023 16:03
-
-
Save Fabianopb/495905864d3cf1be82208b40e3b4818b to your computer and use it in GitHub Desktop.
Node server using multer to upload files to AWS S3.
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
const express = require('express'); | |
const app = express(); | |
const AWS = require('aws-sdk'); | |
const fs = require('fs'); | |
const fileType = require('file-type'); | |
const multiparty = require('multiparty'); | |
// configure the keys for accessing AWS | |
AWS.config.update({ | |
accessKeyId: process.env.AWS_ACCESS_KEY_ID, | |
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY | |
}); | |
// create S3 instance | |
const s3 = new AWS.S3(); | |
// abstracts function to upload a file returning a promise | |
const uploadFile = (buffer, name, type) => { | |
const params = { | |
ACL: 'public-read', | |
Body: buffer, | |
Bucket: process.env.S3_BUCKET, | |
ContentType: type.mime, | |
Key: `${name}.${type.ext}` | |
}; | |
return s3.upload(params).promise(); | |
}; | |
// Define POST route | |
app.post('/test-upload', (request, response) => { | |
const form = new multiparty.Form(); | |
form.parse(request, async (error, fields, files) => { | |
if (error) { | |
return response.status(500).send(error); | |
}; | |
try { | |
const path = files.file[0].path; | |
const buffer = fs.readFileSync(path); | |
const type = await FileType.fromBuffer(buffer); | |
const fileName = `bucketFolder/${Date.now().toString()}`; | |
const data = await uploadFile(buffer, fileName, type); | |
return response.status(200).send(data); | |
} catch (error) { | |
return response.status(400).send(error); | |
} | |
}); | |
}); | |
app.listen(process.env.PORT || 9000); | |
console.log('Server up and running...'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To find the file type use => const type = await fileType.fromBuffer(buffer);
ref: https://www.npmjs.com/package/file-type