0

I want to send some files to server using multipart/form-data. To be more precise I need to send the images to some endpoint(api) with request parameter 'image1'.

The guy that is dealing with the server side said that the 'image1' is required. I suspect my problem is somewhere in the handleSubmit function... But I don't even know if I should append the files like this:

    data.append('image1', state.file) 

or like this:

    data.append('image1', state.file[0]) 
    data.append('image1', state.file[1]) 
    data.append('image1', state.file[2]) 
    data.append('image1', state.file[3]) 

The problem might be something else. I have no idea what.

I visited these links here:

How do I set multipart in axios with react?

How to select multiple files with <input type="file"?>

react-file-upload.js - github example

My code:

functions:

const [state, setState] = useState({
    file: []
})

const onChange = (e) => {
    setState({ file: e.target.files })
}

const handleSubmit = (e) => {
    e.preventDefault(); 
    if (state.file) {
        const data = new FormData()
        //--------------------------------
        // data.append('image1', state.file) // 1 way
        //--------------------------------
        data.append('image1', state.file[0]) // 2 way
        data.append('image1', state.file[1]) // 2 way
        data.append('image1', state.file[2]) // 2 way
        data.append('image1', state.file[3]) // 2 way
        //--------------------------------
     
        api_multy_data.post('/api/some-api', data)
            .then((res) => {
                console.log(res.data)
            }).catch(e => console.log(e))
    }
}

axios/api:

import axios from 'axios'

const api_multy_data = axios.create({
    baseURL: 'http://some_url_here', 
    headers: {
        'content-type': 'multipart/form-data'
    }
})
api_multy_data.interceptors.request.use(
    config => {
        const token = localStorage.getItem('token')
        if (token) {
            config.headers['Authorization'] = `Bearer ${token}`
        }
        return config
    },
    error => Promise.reject(error)
)
export default api_multy_data

Form:

    <form
    enctype='multipart/form-data'
    onSubmit={handleSubmit}>
            <input
             type="file"
             multiple
             onChange={onChange} />
       <button type="submit">Upload</button>
    </form>

Any help Would be much appreciated.

Happy Coconut
  • 865
  • 3
  • 12
  • 27

0 Answers0