Node.js 使用Multer和Formik将图像上载到Mongodb(MERN)
我用MERN创建了一个应用程序。 现在我正试图用Multer和Formik上传图像,但是Node.js 使用Multer和Formik将图像上载到Mongodb(MERN),node.js,reactjs,express,multer,formik,Node.js,Reactjs,Express,Multer,Formik,我用MERN创建了一个应用程序。 现在我正试图用Multer和Formik上传图像,但是req.file返回undefined,我不明白为什么。 这方面我是新手,但我想这可能是由JSON.stringify(http.hook)或内容类型:application/JSON引起的。我也试着用FormData来实现这一点,但这不起作用。有什么想法吗 更新:与邮差合作效果良好。我认为问题在于ui部分,输入并没有传递文件 app.js const {Router} = require('express'
req.file
返回undefined
,我不明白为什么。
这方面我是新手,但我想这可能是由JSON.stringify
(http.hook)或内容类型:application/JSON
引起的。我也试着用FormData
来实现这一点,但这不起作用。有什么想法吗
更新:与邮差合作效果良好。我认为问题在于ui部分,输入并没有传递文件
app.js
const {Router} = require('express');
const multer = require('multer');
const auth = require('../middleware/auth.middleware');
const Users= require('../models/Users');
const router = Router();
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './client/public/uploads/');
},
filename: function (req, file, cb) {
cb(null, file.originalname);
},
});
const upload = multer({
storage: storage,
limits: { fileSize: 10 * 1024 * 1024 }
});
router.post('/create', upload.single('image'), auth, async (req, res) => {
console.log(req.file);
try {
const code = req.body.code;
const existing = await Users.findOne({code: code});
if(existing) {
return res.json({user: existing})
}
const user = new Users(req.body);
await user .save();
res.status(201).json(user);
} catch (e) {
console.log(e);
res.status(500).json({ message: 'Error: try again.' })
}
});
http.hook.js
import {useState, useCallback} from 'react';
export const useHttp = () => {
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const request = useCallback(async (url, method = 'GET', body = null, headers = {}) => {
setLoading(true);
try {
if(body) {
body = JSON.stringify(body);
headers['Content-Type'] = 'application/json';
}
const response = await fetch(url, {method, body, headers});
const data = await response.json();
if(!response.ok) {
throw new Error(data.message || 'Something goes wrong')
}
setTimeout(() => {
setLoading(false);
}, 800);
return data
} catch (e) {
setLoading(false);
setError(e.message);
throw e;
}
}, []);
const clearError = useCallback(() => {setError(null)}, []);
return {loading, request, error, clearError}};
CreateUser.js
import React, {useCallback, useContext, useEffect, useState} from 'react';
import {useHttp} from "../hooks/http.hook";
import Button from "../components/Button/Button";
import {AuthContext} from "../context/auth.context";
import {Formik} from "formik";
export const CreateUser = () => {
const {token} = useContext(AuthContext);
const {loading, request} = useHttp();
const createUser = useCallback(async (body) => {
try {
const fetched = await request(`/api/user/create`, 'POST', body, {
Authorization: `Bearer ${token}`
});
} catch (e) {console.log(e)}
}, []);
const handleCreate = (values, {resetForm}) => {
console.log(values);
createUser(values);
// resetForm({});
};
return (
<div className="wrapper">
<div className="row">
<div className="column small-12 text-center color-white mb_45">
<div className="custom-headline text text-48 font-bold">
<h1>
Crate user
</h1>
</div>
</div>
</div>
<Formik
enableReinitialize
initialValues={{
name: '',
code: '',,
image: null
}}
onSubmit={handleCreate}
>
{({
values,
errors,
touched,
handleBlur,
handleChange,
handleSubmit,
isSubmitting,
setFieldValue,
resetForm
}) => (
<form onSubmit={handleSubmit} className="row align-center">
<div className="column small-12 large-7">
<div className="form-item flex-container align-middle mb_20">
<label className="text text-14 font-semibold font-uppercase text-right small-4">
Photos
</label>
<input id="image" type="file" name="image" className="file_input"
onChange={(event) => {
setFieldValue("image", event.currentTarget.files[0]);
}} />
</div>
</div>
<div className="column small-12 large-7">
<div className="form-item flex-container align-middle mb_20">
<label className="text text-14 font-semibold font-uppercase text-right small-4">
Name
</label>
<input
className="text text-17 "
type="text"
name="name"
onChange={handleChange}
onBlur={handleBlur}
value={values.name}
/>
</div>
</div>
<div className="column small-12 large-7">
<div className="form-item flex-container align-middle mb_20">
<label className="text text-14 font-semibold font-uppercase text-right small-4">
Code
</label>
<input
className="text text-17"
type="text"
name="code"
onChange={handleChange}
onBlur={handleBlur}
value={values.code}
/>
</div>
</div>
<div className="column small-12 mt_20">
<div className="btn_group flex-container flex-wrap align-middle align-center">
<Button className="btn-lg radius-8" theme="blue"
text={Submit} type="submit"
/>
</div>
</div>
</form>
)}
</Formik>
</div>
)
};
import React,{useCallback,useContext,useffect,useState}来自“React”;
从“./hooks/http.hook”导入{useHttp};
从“./组件/按钮/按钮”导入按钮;
从“./context/auth.context”导入{AuthContext};
从“Formik”导入{Formik};
export const CreateUser=()=>{
const{token}=useContext(AuthContext);
const{loading,request}=useHttp();
const createUser=useCallback(异步(主体)=>{
试一试{
const fetched=等待请求(`/api/user/create`、'POST',body{
授权:`Bearer${token}`
});
}catch(e){console.log(e)}
}, []);
常量handleCreate=(值,{resetForm})=>{
console.log(值);
createUser(值);
//resetForm({});
};
返回(
板条箱用户
{({
价值观
错误,
感动的,
车把,
handleChange,
手推,
提交,
setFieldValue,
重置形式
}) => (
照片
{
setFieldValue(“image”,event.currentTarget.files[0]);
}} />
名称
代码
)}
)
};
使用带有multer键“image”的formData包装图像文件
在前端
const handleCreate = async (values) => {
try {
const body = new FormData();
body.append( "image", values.image);
...
} catch (err) {}
};
并确保您的目的地路径使用“dirname”
根据您的目录路径更改此选项我有2-3个建议,
在app.js文件中
router.post('/create', upload.single('image'), auth, async (req, res) => {
console.log(req.file);
在使用upload.single之前,应该先使用auth middelware
您应该使用
{content-type:multipart/form-data}
发送带有POST请求的标题,确定!我不知道这是为什么,但我找到了解决办法——我使用axios
而不是fetch
,当然还有FormData
上传图像或文件,而且很有效希望这对其他人有帮助。谢谢你的回答
const handleCreate = (values, {resetForm}) => {
const formData = new FormData();
formData.append('name', values.name);
formData.append('code', values.code);
formData.append('image', values.image);
axios.post('/api/user/create', formData)
.then(console.log)
catch(console.error);
resetForm({});
};
我尝试了表单数据,仍然得到相同的错误
router.post('/create', upload.single('image'), auth, async (req, res) => {
console.log(req.file);
const handleCreate = (values, {resetForm}) => {
const formData = new FormData();
formData.append('name', values.name);
formData.append('code', values.code);
formData.append('image', values.image);
axios.post('/api/user/create', formData)
.then(console.log)
catch(console.error);
resetForm({});
};