React和Node JS表单图像提交

时间:2019-08-13 19:41:06

标签: javascript reactjs

反应js前端

const AddPost = ({setAlert}) => {

const [post, setPost] = useState({
    name: '',
    subject: '',  
    description: '',
    categories: '',
    errors: {}
});
const [file, setFile] = useState('');
const [category, setCategory] = useState([]);

useEffect(()=>{
    axios.get('/api/categories')
        .then((res)=>{
            setCategory(res.data);
        })
        .catch(err => console.error(err))
},[]);


const {name, subject, description,categories} = post;

const onChangeHandler = e =>{
    setFile(e.target.files[0]);
};

const onChange = e =>{
    setPost({...post, [e.target.name]: e.target.value });
};

const onSubmit = e => {
    e.preventDefault();

    const formData = new FormData();
    formData.append('myImage',file);

    const config = {
        headers:{'Content-Type': 'multipart/form-data'}
    };

    const data = {
        name: name,
        subject: subject,
        description: description,
        categories: categories,
        ...formData
    };

    axios.post('/api/articles/add',data,config)
    .then( res => {
        console.log('success test', res.data);
        setAlert('Article Added','success');
    })
    .catch((err) => {
        console.log('error failed',err);
    });



    setPost({
        name: '',
        subject: '',
        description: '',
        categories: '',
    });
    setFile({file:''})
};



return (
    <Fragment>
        <div className="container">
            <div className="row justify-content-center">
                <div className="col-6">
                    <h3>Add Posts</h3>
                    <form onSubmit={e => onSubmit(e)}>
                        <div className="form-group">
                            <input
                                type="text"
                                name='name'
                                value={name}
                                className="form-control"
                                placeholder="Authors name"
                                onChange={e => onChange(e)}
                            />
                        </div>
                        <div className="form-group">
                            <input
                                type="text"
                                name='subject'
                                value={subject}
                                className="form-control"
                                placeholder="subject"
                                onChange={e => onChange(e)}
                            />
                        </div>

                        <div className="form-group">
                            <select  name='categories'
                                     value={categories}
                                     onChange={e => onChange(e)}
                                     className="form-control">
                                <option selected>Choose category</option>
                                {
                                    category.map((item,index)=>(
                                <option key={index}
                                    >{item.name}
                                </option>
                                    ))
                                }
                            </select>
                        </div>

                        <div className="form-group">
                        <textarea
                            rows="6"
                            className="form-control"
                            name='description'
                            value={description}
                            placeholder="content"
                            onChange={e => onChange(e)}> </textarea>
                        </div>


                        <input type="file" name='myImage' onChange={e => onChangeHandler(e)} />

                        <button type="submit" className="btn btn-primary">Submit</button>
                    </form>
                </div>
            </div>
        </div>
    </Fragment>
   );
};

这是节点后端的代码

router.post('/add',(req,res) => {

    upload(req,res,(err) => {
        if(err){
            res.send(err);
        }else{
            console.log(req.file);
            res.send('test');
        }
    });

var name = req.body.name;
var subject = req.body.subject;
var description = req.body.description;
var categories = req.body.categories;


if(req.file){
    var myImage = req.file.filename
}else{
    myImage = 'noImage2.jpg'
}

newArticle = new Article({
    name: name,
    subject: subject,
    description: description,
    categories: categories,
    image: myImage
});

newArticle.save();
   try{ res.send('success')}
   catch{res.status(400).json('error')}
});`

我有一个反应博客,其中包含作者的姓名,标题,正文和图像,我在节点服务器中使用multer来处理图像上传,但是我不知道如何将图像和其他表单数据一起发送。我可以分开寄给他们。但是我需要将它们一起发送,我已经尝试过formData。请任何帮助将不胜感激。

0 个答案:

没有答案