node.js multer saving file name into db

5.8k views Asked by At

I'm trying to save uploaded file name into db? thanks. Basically how can I pass multer file.name into database. My attempt is using this var: var fileimage = file.name;

router.use(multer({ // https://github.com/expressjs/multer
  dest: './uploads/', 
  limits : { fileSize:100000 },
  rename: function (fieldname, filename) {
    return filename.replace(/\W+/g, '-').toLowerCase();
  },
  onFileUploadData: function (file, data, req, res) {
    // file : { fieldname, originalname, name, encoding, mimetype, path, extension, size, truncated, buffer }
    var params = {
      Bucket: 'lemybucket01',
      Key: file.name,
      Body: data
    };

    s3.putObject(params, function (perr, pres) {
      if (perr) {
        console.log("Error uploading data: ", perr);
      } else {
        console.log("Successfully uploaded data to myBucket/myKey");
      }
    });
  },
  onFileUploadComplete: function (file) {
    var fileimage = file.name;
  }
}));

router.route('/')
    //POST a new prod
    .post(function(req, res) {

        if(req.files.fileimage !== undefined){ // `image` is the field name from your form
            //res.redirect("/uploads"); // success
        }else{
            res.send("error, no file chosen");
        }

        // Get values from POST request. These can be done through forms or REST calls. These rely on the "name" attributes for forms

        var username = req.body.username;

        //call the create function for our database
        mongoose.model('Prod').create({
            username : username,
            fileimage : fileimage
        }, function (err, prod) {
              if (err) {
                  res.send("There was a problem adding the information to the database.");
              } else {
                  //Prod has been created
                  console.log('POST creating new prod: ' + prod);
                  res.format({
                      //HTML response will set the location and redirect back to the home page. You could also create a 'success' page if that's your thing
                    html: function(){
                        // If it worked, set the header so the address bar doesn't still say /adduser
                        res.location("prods");
                        // And forward to success page
                        res.redirect("/prods");
                    },
                    //JSON response will show the newly created prod
                    json: function(){
                        res.json(bloprodb);
                    }
                });
              }
        })
    });
1

There are 1 answers

0
xdevel On BEST ANSWER

The req.files.fileimage !== undefined is always false?

The variable fileimage you declared in the following has limited scope

onFileUploadComplete: function (file) {
  var fileimage = file.name;
}

If you want to pass some data(like fileimage) from one middleware to another you can use something like this.

onFileUploadComplete: function (file, req, res) {
  var fileimage = file.name;
  req.middlewareStorage = {
    fileimage : fileimage//,
    //otherKey : otherValue
  }
}

and you can save in the db as

var fileimage = req.middlewareStorage.fileimage;
mongoose.model('Prod').create({
    username : username,
    fileimage : fileimage
}, function (err, prod) {
  // do some stuff
});