简体   繁体   中英

saving uploaded file in project directory using multer

i am able to upload files in node.js using middleware called multer.but when i give destination path : '/uploads/'. files are saved in c: drive

var express = require('express');
var router = express.Router();


var multer = require('multer');
var storage = multer.diskStorage({
  destination: function (req, file, cb) {
   cb(null, '/uploads/')
   },
   filename: function (req, file, cb) {
     cb(null, file.originalname)
   }
 })

  var upload = multer({storage: storage});

   var emp = require('../models/employees.js');

  router.post('/', upload.single('file'), function(req,res,next){
    console.log("Server: got file ");
    console.log(req.file);
    var upl = new emp({picture: req.file.originalname});
         upl.save(function(err,docs) {
           if (err) {
            console.log(err);
            }
              res.json(docs);
         });
  });
  module.exports = router;

i tried to give a long string path too like

'/users/user/webstormprojects/template/public/uploads/image/'

but it ends with internal server error someone please help me so that i can be able to save my uploaded files into my project directory.

Try using Path Module.And then use _dirname. See the code below

var path = require('path') var storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, path.join(__dirname + '/uploads/')) }, filename: function (req, file, cb) { cb(null, file.originalname) } })

This should solve your problem. _dirname will give you the access of the directory you are working in.

Add this line in your app.js or index.js file

app.use(express.static(__dirname + '/public', { maxAge: week }));

then upload your files inside /uploads like this

destination: function (req, file, callback) {
    callback(null, './public/uploads');
},

NB: make sure that there is uploads folder inside public folder

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