Search code examples
reactjsfile-uploadfrontendmulter

Can't upload multiple files by using Multer on React


Multer worked fine when I upload multiple images by using Postman but when I try to send files as an array from the front-end, it always return files is undefined and files is not iterable.

I think the problem is in the front-end React. How to fix this problem?

Back-end

 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)

.
.
.
      

Front-end React

 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>


)
    
    }

Solution

  • I found the problems and I fixed it by using formData in handleSubbmitFile and set the property filed to image by using append.

    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);
        
    }
    

    Another problems is that using Json.stringify() before using axios. I didn't use Json.stringify() to convert formData before sending it to back-end via axios. As a result, Multer work well without problems

    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);
            }
        }