gpt4 book ai didi

node.js - Express multer 上传不起作用

转载 作者:搜寻专家 更新时间:2023-10-31 23:40:22 24 4
gpt4 key购买 nike

我的 uploader 有问题。我认为所有带有代码的东西都是正确的,但文件仍然没有在上传文件夹中创建。此外,当我尝试 console.log(req.files) 时,我得到一个空数组。我尝试在本地制作这是代码:

const   express = require("express"),
app = express(),
multer = require("multer"),
bodyParser=require("body-parser"),


app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

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

var upload = multer({ storage : storage }).array('userPic');

app.post("/postFormAct", isLoggedIn, function(req, res){
upload(req,res,function(err) {
console.log(req.files);
});
});

还有我的表格:

<form method="post" action="/postFormAct" enctype="multipart/form-data">
<input type="text" name="user"><br>
<input type="text" name="email"><br>
<input type="file" name="userPic"><br>
<input type="submit" value="Submit">
</form>

最佳答案

我认为你的功能级中间件有问题,你有 isLoggedIn,你必须像这样立即链接 multer 中间件 upload :

// ...
var upload = multer({ storage : storage }).array('userPic');

app.post("/postFormAct", isLoggedIn, upload, function(req, res){
console.log(req.files)
});

这是一个完整的工作示例:

const app = require('express')()
const bodyParser = require('body-parser')
const multer = require('multer')
const morgan = require('morgan')

const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'uploads')
},
filename: (req, file, cb) => {
cb(null, file.fieldname + '-' + Date.now())
}
})

const upload = multer({
storage: storage
})

app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.use(morgan('dev'))

isLoggedIn = (req, res, next) => {
console.log('check if user is logged in')
next()
}

app.post('/uploads', isLoggedIn, upload.array('images'), (req, res) => {
console.log(req.files);
return res.send(req.files);
})

app.listen(8000, () => {
console.log(`server is listenning on port 8000`)
})

您可以找到一个测试存储库 here

还要确保您的目标目录存在。

关于node.js - Express multer 上传不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46987140/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com