Monday 5 June 2017

Refactor: Upload multiple images - NodeJS & Amazon S3

I've been trying to figure out how to upload several images at once using Amazon S3, NodeJS, MongoDB, and Multer. I have figured it out and it is working... but I feel like what I have come up with should NOT be working. I'm afraid it may be super unstable and end up crashing my web app.

Is this the correct way to handle uploading and displaying images with S3/Node and how could I refactor my code?

Thanks for any help of advice!

aws.config.update({
    secretAccessKey: '*********************',
    accessKeyId: '***********',
    region: 'us-east-2'
});
var s3 = new aws.S3();
var upload = multer({
    storage: multerS3({
        s3: s3,
        bucket: 'mybucketname',
        key: function (req, file, cb) {
            var fileExtension = file.originalname.split(".")[1];
            var path = "uploads/" + req.user._id + Date.now() + "." + fileExtension;
            cb(null, path); 
        },

//Not sure if below is doing anything...

    destination: function(req, file, callback) {
    callback(null, './public/uploads');
  },
  filename: function(req, file, callback) {
    callback(null, Date.now() + file.originalname);
  }
    })
});

Then in my post route:

router.post("/", middleware.isLoggedIn, upload.array('image', 4), function(req, res, next){
    // get data from form and add to campgrounds array

      var filepath = undefined;

      var filepath2 = undefined;


    if(req.files[0]) {
        filepath = req.files[0].key;
    } 

      if(req.files[1]) {
        filepath2 = req.files[1].key;
    } 

    var name = req.body.name;
    var image = filepath;
    var image2 = filepath2;
    var desc = req.body.description;
   var newCampground = {name: name, image: image, image2: image2, description: desc}

    // Create a new campground and save to DB
    Campground.create(newCampground, function(err, newlyCreated){
        if(err){
            console.log(err);
        } else {
            //redirect back to campgrounds page
            res.redirect("/campgrounds");
        }
    });
    });
});

And then on my show page:

   <% if(campgrounds.image) { %>

                         <% var imgsrc = awspath + campgrounds.image; %>
                         <img class="image-resposive" src=<%=imgsrc%>

           <% } %>

   <% if(campgrounds.image2) { %>

                         <% var imgsrc = awspath + campgrounds.image2; %>
                         <img class="image-resposive" src=<%=imgsrc%>

           <% } %>



via AndrewLeonardi

No comments:

Post a Comment