Search code examples
javascriptreactjsreact-dropzone

How to convert image data to multipart /form-data


I am using react-dropzone-uploader for uploading my image to an API but the API needs the data in multipart/form-data. I am not able to convert it into form-data.

Here is my code :

const onDropHandler = (files) => {
    let formData= new FormData()
    formData.append('file',files[0])
    axios.post('/web/v1.0/upload',{formData}).then(response=>{
    console.log(response.data)
})

I am getting this error:

401 unauthorized


Solution

  • You'll need to set the Content-Type header to 'multipart/form-data'

    Give this a try:

    const onDropHandler = (files) => {
        const headers = {
          'Content-Type': 'multipart/form-data'
        }
        let formData = new FormData()
        formData.append('file', files[0])
        API.post('/web/v1.0/upload', {
          formData
        }, {
          headers: headers
        }).then(response => {
          console.log(response.data)
        })
    

    PS: I'm assuming that your API.post method accepts a config Object that supports headers.