首页 > 解决方案 > 无法在 React 上使用 Multer 上传多个文件

问题描述

当我使用 Postman 上传多个图像时,Multer 工作正常,但是当我尝试从前端将文件作为数组发送时,它总是返回文件未定义且文件不可迭代。

我认为问题出在前端 React 中。如何解决这个问题?

后端

 router.post('/multer',auth ,upload.array('image'), async (req, res) => { //NOTE image is the field name
        try {
            const urls = []
            const files = req.files; 
            console.log('Upload cloudinary running '+ files)

.
.
.
      

前端反应

 import React, {Fragment, useState, useEffect} from 'react';
    
    const Dashboard = ({auth: { user, loading }}) => {
.
.
.
     
        const [files, setFiles] = useState([]);
        const handleChange = e => {
            const file_reader = new FileReader();
            const file = e.target.files[0];
            let file = e.target.files[0];
            file_reader.onload = () => {
              setFiles([...files, { image: file_reader.result }]);
             
            };
            file_reader.readAsDataURL(file);
                }
        
        const handleSubbmitFile = (e) => {
                e.preventDefault();
                if(!files) return; 
                uploadImage(files);
                
            }
        
         const uploadImage = async (base64EncodedImage) => {
                try {     
                    const config = {
                        headers:{
                            'Content-Type' :  'application/json'
                        }
                    }
                    const body = JSON.stringify({files: base64EncodedImage});
                    await axios.post('/api/blogs/multer', body, config);     
                    
                } catch (error) {
                    console.log(error);
                }
        }
            return(
                    <form onSubmit={handleSubbmitFile} className="form-outline">
                            <input name="image" onChange={handleChange} type="file" 
                            class="form-control-file" id="exampleFormControlFile1"  
                            accept="image/*"/>  
                    </form>


)
    
    }

标签: reactjsfile-uploadfrontendmulter

解决方案


我发现了问题,并通过在 handleSubbmitFile 中使用 formData 来修复它,并使用 append 将属性字段设置为 image。

const handleSubbmitFile = (e) => {
    e.preventDefault(); //NOTE prevent from reload the page 
    let formData = new FormData(); 
    for(var i = 0 ; i < files.length; i++){
        formData.append('image',files[i])
    }
    if(!files) return; 
    uploadImage(formData);
    
}

另一个问题是在使用 axios 之前使用 Json.stringify()。在通过 axios 将其发送到后端之前,我没有使用 Json.stringify() 来转换 formData。结果,Multer 运行良好,没有问题

const uploadImage = async (formData) => {
        try {
            const config = {
                headers:{
                    'Content-Type' :  'application/json'
                }
            }
            await axios.post('/api/blogs/multer', formData, config);
        } catch (error) {
            console.log(error);
        }
    }

推荐阅读