node.js - nodejs multer 正在获取 req.file 但未将其上传到目的地

标签 node.js file express upload multer

multer.js

var path = require("path"),
multer = require("multer");

const storage = multer.diskStorage({
    destination: function(req, file, next){
        next(null, '../public/imgs/');
        return;
    },
    filename: function(req, file, cb){
        cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
    }
});

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

module.exports = upload;

路由器.js

//handle createPartner route
router.post("/partner/new", upload.single('image'), function(req, res){

  console.log(req.file);
  console.log(req.body);

  req.body.Partner["image"] ="/static/imgs/"+req.file.filename;

  req.body.Partner.body = req.sanitize(req.body.Partner.body);

  Partner.create(req.body.Partner, function(err, createdPartner){
      if(err){
          console.log(err);
          res.redirect("/admin/partner/new");
      }else{
          res.redirect("/partners");
      }
  });
});

我得到以下console.log

{ fieldname: 'image',
  originalname: 'fb.png',
  encoding: '7bit',
  mimetype: 'image/png',
  destination: '../public/imgs/',
  filename: 'image-1521727739861.png',
  path: '../public/imgs/image-1521727739861.png',
  size: 21532 }
{ Partner: { name: 'test', bio: 'test', image: '', website: 'test' } }

所以 multer 确实获取了文件,但没有将其上传到目的地!/public 和/public/imgs 的权限是 777。我搜索的所有地方都使用其他 multer 方法,但这样我就必须提前指定(单个/多个/任意),这是不正确的。

最佳答案

您需要包含我在评论中提到的绝对路径。

您可以通过使用 path.join 轻松完成此操作,如下所示:

var path = require('path');
var dir = path.join(__dirname, '../public/imgs')

这会将当前文件的绝对路径 __dirname 与图像文件连接起来。

关于node.js - nodejs multer 正在获取 req.file 但未将其上传到目的地,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49430962/

相关文章:

node.js - 从 request.connection.remoteAddress nodejs 中剥离 "::ffff:"前缀

c++ - 哪种设计模式便于维护数据文件的向后兼容性?

node.js - 我们可以将 multer 配置为不在本地存储文件并且仅用于使用 req.files.image.path 吗?

Node.js + Express - 如何让 mustache 部分工作?

javascript - Buffer 和 TypedArray 转换导致数据突变?

node.js - 为 npm 整数安装 node-gyp 错误

javascript - 所有 Mongoose 模型方法都是基于 promise 的吗?

linux - Linux 文件系统中的读取访问权限。 rwx---r--

c++ - 如何检查文件是否存在于目录中?

javascript - 图像未上传到nodejs中的数据库