简体   繁体   中英

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");
            }
        });
    });

You didn't mention where the error was appearing, but based on your code, it seems that req.files is undefined. You probably need to add the appropriate middleware for handling file uploads.

Really though, if you're accepting posts from web users, you should just have them upload to S3 directly using a pre-signed URL or upload form. Save yourself the hassle and the bandwidth.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM