为什么我的图片在随机文件夹中上传,multer无法正常工作

时间:2018-07-11 13:14:46

标签: node.js file-upload path multer

  var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, ' /uploads')
  },
  filename: function (req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now() + '.jpg' );
  }

  });

var upload = multer({ storage: storage }).single('image');

app.post('/blog',function (req, res) {
 // use upload var
  upload(req, res, function (err) {
    if (err) {
        console.log(err);
         return
    }
    //get image form form
var image = req.files.image;
console.log( req.files);
          Blog.create(image, function(err, newlyCreated){

    if (err) {
      // An error occurred when uploading
      console.log(err);
    }
    res.redirect("/blog");
    })
    // Everything went fine
  });

  });

并显示此结果:

{ image:
   { fieldName: 'image',
     originalFilename: 'back-1.jpg',
     path: 'C:\\Users\\Lenovo\\AppData\\Local\\Temp\\11964-2kgi7t.18voswcdi.jpg',
     headers:
      { 'content-disposition': 'form-data; name="image"; filename="back-1.jpg"',
        'content-type': 'image/jpeg' },
     ws:
      WriteStream {
        _writableState: [Object],
        writable: false,
        domain: null,
        _events: [Object],
        _eventsCount: 2,
        _maxListeners: undefined,
        path: 'C:\\Users\\Lenovo\\AppData\\Local\\Temp\\11964-2kgi7t.18voswcdi.jpg',
        fd: null,
        flags: 'w',
        mode: 438,
        start: undefined,
        autoClose: true,
        pos: undefined,
        bytesWritten: 148998,
        closed: true },
     size: 148998,
     name: 'back-1.jpg',
     type: 'image/jpeg' 
  } 
}

1 个答案:

答案 0 :(得分:0)

我想您在目标目录之前错过了一个.(点),您需要更改以下代码,

destination: function (req, file, cb) {
  cb(null, ' /uploads')
}

收件人

destination: function (req, file, cb) {
  cb(null, './uploads/')
}

希望这会有所帮助!