Home > Back-end >  How to get image url location from Aws s3 and store it in mongodb
How to get image url location from Aws s3 and store it in mongodb

Time:11-19

I need a URL location of an image from AWS s3 and store it in MongoDB with mongoose. At this point when I console log, req.file.location value is undefined. I have also tried console log uploadFile and here i get proper location... but how can i fetch it in my new rope image?

S3.js:

require('dotenv').config()
const fs = require('fs')
const S3 = require('aws-sdk/clients/s3')


const bucketName = process.env.AWS_BUCKET_NAME
const region = process.env.AWS_BUCKET_REGION
const accessKeyId = process.env.AWS_ACCESS_KEY
const secretAccessKey = process.env.AWS_SECRET_KEY


const s3 = new S3({
    region,
    accessKeyId,
    secretAccessKey
})

function uploadFile(file){
    const fileStream = fs.createReadStream(file.path)

    const uploadParams = {
        Bucket:bucketName,
        Body:fileStream,
        Key: `image-${Date.now()}.jpeg`
    }

    return s3.upload(uploadParams).promise()
}

exports.uploadFile = uploadFile

product.vue:

const upload = multer({
  dest:'uploads/'
})

const {uploadFile} = require('../s3')


router.post('/', upload.single('image'), async (req, res) => {

    console.log(req.file.location)
    const rope = new Rope({
        title: req.body.title,
        description: req.body.description,
        image: req.file.location,
        price: req.body.price,
        cartQuantity: req.body.cartQuantity,

    });
    try {
        await uploadFile(req.file)
        await rope.save();
        res.status(201).json(rope);
        console.log(req.body)
    } catch (err) {
        res.status(400).send(err);
    }
});

CodePudding user response:

Seem like you misplaced uploadFile line. You need to upload the file first, then get the url and put it to Rope payload

router.post('/', upload.single('image'), async (req, res) => {

const fileUploaded = await uploadFile(req.file)
const { Location } = fileUpload
const rope = new Rope({
    title: req.body.title,
    description: req.body.description,
    image: Location,
    price: req.body.price,
    cartQuantity: req.body.cartQuantity,

});
  try {
    await rope.save();
    res.status(201).json(rope);
    console.log(req.body)
  } catch (err) {
    res.status(400).send(err);
  }
});
  • Related