req.file 未定义多个文件上传
req.file is undefined for multiple file uploads
我已经通读了这里所有可能的答案,但我不再确定问题出在哪里,因为其中 none 个答案有效。我有一个上传单个图像的表单,它按预期工作,但在我尝试上传多个文件并有表单输入的不同表单上,req.file 始终未定义,图像数据最终在 req.body。所以在某个地方我认为可能存在 multer 没有获取文件数据的问题...?
我在几个地方读到 body-parser 可能不能很好地与 multer 一起玩,但不幸的是我需要它们。
路线
const destination = './public/uploads/posts';
const storage = multer.diskStorage({
destination: destination,
filename: (req, file, cb) => {
cb(null, file.originalname);
},
});
const upload = multer({storage}).array('images');
router.post('/posts', (req, res) => {
upload(req, res, (err) => {
if(err) {
console.log('errors', err)
res.json({success: false, error: err})
} else {
if(req.files === undefined) {
console.log('error: Images returned undefined');
} else {
const { title, description, url, auth_name, auth_id } = req.body;
if(!title || !description) {
return res.json({
success: false,
error: 'All fields required',
message: 'Title and description fields are required'
});
}
// path we store in the db
let imageLocation = [];
const post = new Post();
for (const file of req.files) {
imageLocation.concat('/uploads/posts/' + file.filename)
}
post.title = title;
post.description = description;
post.url = url;
post.author_name = auth_name;
post.author = auth_id;
post.images = imageLocation;
post.save((err, post) => {
if(err) {
return res.json({ success: false, error: err, message: 'post failed' });
} else {
return res.json({ success: true, message: "added new post", post: post });
}
});
}
}
});
});
post 反应组件
我的图像设置为我从 DropZone 包中获得的状态(我在没有 DropZone 的情况下进行了测试,结果相同。我确保输入名称是 "images"
submitNewPost = () => {
const { title, description, url, images } = this.state;
const auth_id = this.props.author_id;
const auth_name = this.props.author_name;
const formdata = new FormData();
formdata.append('title', title);
formdata.append('description', description);
formdata.append('url', url);
formdata.append('author_name', auth_name);
formdata.append('author', auth_id);
formdata.append('images', images);
fetch('/api/posts', {
method: 'POST',
body: formdata
}).then(res => res.json())
.then((res) => {
if (!res.success) {
this.setState({ message: res.message });
} else {
this.setState({
title: '',
description: '',
url: '',
images: '',
message: res.message
});
socket.emit('newPost', res.post);
}
});
}
更新
在这方面的一些帮助下 thread 我设法使用现有路线和 postman 上传了图像。当我使用我的表单测试路线时,我仍然得到一个空的 req.file 并且没有上传。
我在我的设置中添加了 express-multipart-file-parser,我认为这让我离解决这个问题又近了一步。
服务器
这是我添加到 server.js
中的内容
import { fileParser } from 'express-multipart-file-parser';
app.use(fileParser({
rawBodyOptions: {
limit: '15mb', //file size limit
},
busboyOptions: {
limits: {
fields: 20 //Number text fields allowed
}
},
}));
要正确填充 req.files
,您需要像这样使用 formdata.append
:
images.forEach(image => {
formdata.append('images', image);
})
您缺少使用数组传递值。
router.post('posts', upload.array('image', 10), function (req, res, next) {
})
感谢所有帮助。我设法修好了。原来我在我的状态下将 FileList 对象连接到一个数组,所以结构完全错误并且在服务器上它只是失败了。我的图片现在可以完美上传了。
如果我发布了我的 React 组件的那一部分,我相信你们中的任何人都会在一秒钟内看到它,抱歉。我没有想到问题出在我的组件中。
问题
onFileLoad = (e) => {
this.setState({
images: this.state.images.concat(e.target.files)
});
}
修复
onFileLoad = (e) => {
this.setState({
images: e.target.files
});
}
submitMediaPOst = () => {
const imageArr = Array.from(images);
imageArr.forEach(image => {
formdata.append('images', image);
});
...
我已经通读了这里所有可能的答案,但我不再确定问题出在哪里,因为其中 none 个答案有效。我有一个上传单个图像的表单,它按预期工作,但在我尝试上传多个文件并有表单输入的不同表单上,req.file 始终未定义,图像数据最终在 req.body。所以在某个地方我认为可能存在 multer 没有获取文件数据的问题...?
我在几个地方读到 body-parser 可能不能很好地与 multer 一起玩,但不幸的是我需要它们。
路线
const destination = './public/uploads/posts';
const storage = multer.diskStorage({
destination: destination,
filename: (req, file, cb) => {
cb(null, file.originalname);
},
});
const upload = multer({storage}).array('images');
router.post('/posts', (req, res) => {
upload(req, res, (err) => {
if(err) {
console.log('errors', err)
res.json({success: false, error: err})
} else {
if(req.files === undefined) {
console.log('error: Images returned undefined');
} else {
const { title, description, url, auth_name, auth_id } = req.body;
if(!title || !description) {
return res.json({
success: false,
error: 'All fields required',
message: 'Title and description fields are required'
});
}
// path we store in the db
let imageLocation = [];
const post = new Post();
for (const file of req.files) {
imageLocation.concat('/uploads/posts/' + file.filename)
}
post.title = title;
post.description = description;
post.url = url;
post.author_name = auth_name;
post.author = auth_id;
post.images = imageLocation;
post.save((err, post) => {
if(err) {
return res.json({ success: false, error: err, message: 'post failed' });
} else {
return res.json({ success: true, message: "added new post", post: post });
}
});
}
}
});
});
post 反应组件
我的图像设置为我从 DropZone 包中获得的状态(我在没有 DropZone 的情况下进行了测试,结果相同。我确保输入名称是 "images"
submitNewPost = () => {
const { title, description, url, images } = this.state;
const auth_id = this.props.author_id;
const auth_name = this.props.author_name;
const formdata = new FormData();
formdata.append('title', title);
formdata.append('description', description);
formdata.append('url', url);
formdata.append('author_name', auth_name);
formdata.append('author', auth_id);
formdata.append('images', images);
fetch('/api/posts', {
method: 'POST',
body: formdata
}).then(res => res.json())
.then((res) => {
if (!res.success) {
this.setState({ message: res.message });
} else {
this.setState({
title: '',
description: '',
url: '',
images: '',
message: res.message
});
socket.emit('newPost', res.post);
}
});
}
更新
在这方面的一些帮助下 thread 我设法使用现有路线和 postman 上传了图像。当我使用我的表单测试路线时,我仍然得到一个空的 req.file 并且没有上传。
我在我的设置中添加了 express-multipart-file-parser,我认为这让我离解决这个问题又近了一步。
服务器
这是我添加到 server.js
中的内容 import { fileParser } from 'express-multipart-file-parser';
app.use(fileParser({
rawBodyOptions: {
limit: '15mb', //file size limit
},
busboyOptions: {
limits: {
fields: 20 //Number text fields allowed
}
},
}));
要正确填充 req.files
,您需要像这样使用 formdata.append
:
images.forEach(image => {
formdata.append('images', image);
})
您缺少使用数组传递值。
router.post('posts', upload.array('image', 10), function (req, res, next) {
})
感谢所有帮助。我设法修好了。原来我在我的状态下将 FileList 对象连接到一个数组,所以结构完全错误并且在服务器上它只是失败了。我的图片现在可以完美上传了。
如果我发布了我的 React 组件的那一部分,我相信你们中的任何人都会在一秒钟内看到它,抱歉。我没有想到问题出在我的组件中。
问题
onFileLoad = (e) => {
this.setState({
images: this.state.images.concat(e.target.files)
});
}
修复
onFileLoad = (e) => {
this.setState({
images: e.target.files
});
}
submitMediaPOst = () => {
const imageArr = Array.from(images);
imageArr.forEach(image => {
formdata.append('images', image);
});
...