Created
June 26, 2020 17:16
-
-
Save iamEtornam/f42e4cd2d695a0cb51843ce01d7ba4aa to your computer and use it in GitHub Desktop.
uploading files to aws s3 bucket using nodejs
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 router = express.Router(); | |
| const upload = require('../services/uploder_service'); | |
| const singleUpload = upload.single('image'); | |
| router.post('/image-upload', function(req, res) { | |
| singleUpload(req, res, function(err) { | |
| if (err) { | |
| return res.status(401).send( | |
| { | |
| message: 'Image Upload Error', | |
| detail: err.message | |
| }); | |
| } | |
| return res.status(200).send({ | |
| imageUrl: `${req.file.location}` | |
| }); | |
| }); | |
| }); | |
| module.exports = router; |
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 aws = require('aws-sdk'); | |
| const multer = require('multer'); | |
| const multerS3 = require('multer-s3'); | |
| const env = process.env.NODE_ENV || 'aws_credentials'; | |
| const config = require('../../config/config.json')[env]; | |
| aws.config.update({ | |
| secretAccessKey: config.secretAccessKey, | |
| accessKeyId: config.accessKeyId, | |
| region: config.region | |
| }); | |
| const s3 = new aws.S3(); | |
| const upload = multer({ | |
| storage: multerS3({ | |
| acl: 'public-read', | |
| s3, | |
| bucket: config.bucket, | |
| contentType: multerS3.AUTO_CONTENT_TYPE, | |
| metadata: function (req, file, cb) { | |
| cb(null, Object.assign({}, req.body)); | |
| }, | |
| key: function (req, file, cb) { | |
| cb(null, `${Date.now()}-${file.originalname}`) | |
| } | |
| }) | |
| }); | |
| module.exports = upload; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment