multer上传文件后无法跳转页面
发布于 1 个月前 作者 Chensonghao 607 次浏览 来自 问答

问题:

如下代码,能正常上传文件,但是页面无法跳转,经调试,当选择文件后上传没有进入到uploadFile回调函数内,而不选择文件直接提交就可以,为什么啊

var multer = require('multer');
var storage = multer.diskStorage({
    destination: function(req, file, cb) {
        cb(null, './public/images/')
    },
    filename: function(req, file, cb) {
        cb(null, file.originalname)
    }
 })
var uploadFile = multer({
storage: storage
}).single('file1');
app.post('/upload', function(req, res) {
    uploadFile(req, res, function(err) {
        console.log('测试是否可以到达。');
        if (err) {
            console.log(err);
        } else {
        }
        res.redirect('/upload');
    })
6 回复

用错了,看文档去

@i5ting 我就是看着文档写的啊,哪里用错了,请告知,万分感谢

single处位置不对

filename改成下面这样就行了,我可以理解为文件名中一定要包含一个时间戳才行吗。。。

filename: function(req, file, cb) {
    var fileFormat = (file.originalname).split(".");
    cb(null, file.originalname + '-' + Date.now() + "." + fileFormat[fileFormat.length - 1]);
}
var express = require('express')
var multer  = require('multer')
var upload = multer({ dest: 'uploads/' })

var app = express()

app.post('/profile', upload.single('avatar'), function (req, res, next) {
  // req.file is the `avatar` file
  // req.body will hold the text fields, if there were any
})

app.post('/photos/upload', upload.array('photos', 12), function (req, res, next) {
  // req.files is array of `photos` files
  // req.body will contain the text fields, if there were any
})

var cpUpload = upload.fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }])
app.post('/cool-profile', cpUpload, function (req, res, next) {
  // req.files is an object (String -> Array) where fieldname is the key, and the value is array of files
  //
  // e.g.
  //  req.files['avatar'][0] -> File
  //  req.files['gallery'] -> Array
  //
  // req.body will contain the text fields, if there were any
})

@i5ting 谢谢,回家在macbook上试了一切正常,应该是windows系统的bug吧。。。

回到顶部