Wednesday, 17 May 2017

Upload to S3 using aws-sdk and Node/Express

I've been following this guide Simple file upload to S3 using aws-sdk and Node/Express to attempt to let users upload images via S3. For some reason I cannot get it to work. How would I fix my code to correct the error?

The error I get is: TypeError: Cannot read property '0' of undefined.

    var aws             = require('aws-sdk');
    var multerS3        = require('multer-s3');
    var  multer          = require("multer");

    (Not real codes)
    aws.config.update({
        secretAccessKey: 'QWUdawup',
        accessKeyId: 'GHQWD1A',
        region: 'us-east-2'
    });

       var s3 = new aws.S3();

    var upload = multer({
        storage: multerS3({
            s3: s3,
            bucket: 'medstayfiles',
            key: function (req, file, cb) {
                console.log(file);
                cb(null, file.originalname); //use Date.now() for unique file keys
            }
        })
    });



router.post("/", middleware.isLoggedIn, upload.array('image', 1), function(req, res,next){

        var filepath = undefined;
        if(req.files[0]) {
            filepath = req.files[0].key; // 'uploads/xxxxx.extension'
        }

        var newRentals = {filepath: filepath}

        Rentals.create(newRentals, function(err, newlyCreated){
            if(err){
                console.log(err);
            } else {
                //redirect back to rentals page
                res.redirect("/rentals");
            }
        });
    });



via AndrewLeonardi

No comments:

Post a Comment