0
votes

I want to upload an image with axios in react native. This is my function which call upload image web service api:

function _uploadImgToServer(item) {

        const file = {
            uri: item.imgData.path,
            type: item.imgData.mime,
            name: 'ana' + item.imgId
        }
        const body = new FormData();
        body.append('file', file);
        console.log('uploadResult saga0', body)
        dispatch(uploadImg({ body: JSON.stringify(body)}))
    } 

this is my axios config:

const instance = axios.create({
        baseURL: '****',
        responseType: 'json',
        timeout: 10000,
        headers: {
            'WEB_TOKEN': '*****',
            'UNIQUE_ID': '*****',
            'UNIQUE_KEY': '*****',
             Accept: "application/json",
            'Content-Type':  "multipart/form-data"
        },
    });

And I call my web service like bellow:

try {
    const response = await instance.post(url, data);
    return Promise.resolve(response.data);
} catch (error) {
    return Promise.reject(error.response);
}

Part of the response I get in last part is:

'My log result' { data: { Code: 3, Message: 'Invalid Entry', Value: null },
  status: 200,
  statusText: undefined,
  headers: 
   {
    ...

     'content-type': 'application/json; charset=utf-8',

    ...

   },
  config: 
   { url: 'upload',
     method: 'post',
     data: '{"_parts":[[{"uri":"file:///data/data/***packageName***/cache/react-native-image-crop-picker/IMG-20201222-WA0017.jpg","type":"image/jpeg","name":"ana_pu8kweg4e"},null]]}',
     headers: 
      { Accept: 'application/json',
        'Content-Type': 'multipart/form-data',
        WEB_TOKEN: '*****',
        UNIQUE_ID: '****',
        UNIQUE_KEY: '****' },
     baseURL: '****',
     transformRequest: [ [Function: transformRequest] ],
     transformResponse: [ [Function: transformResponse] ],
     timeout: 10000,
     adapter: [Function: xhrAdapter],
     responseType: 'json',
     xsrfCookieName: 'XSRF-TOKEN',
     xsrfHeaderName: 'X-XSRF-TOKEN',
     maxContentLength: -1,
     maxBodyLength: -1,
     validateStatus: [Function: validateStatus] },

 ...
}

As you see in my log result, the content-type in header I have sent is 'multipart/form-data' but server has received 'application/json; charset=utf-8' so I cannot upload my image. It is worth to mention that if I do not use JSON.stringify, content-type will not be sent at all. I have searched a lot but I could not find any useful response.

1

1 Answers

1
votes

I found that my problem was not about "content-type" at all. I had to put image type at the end of the image name.

const file = {
            uri: item.imgData.path,
            type: item.imgData.mime,
            name: 'ana'+item.imgId+'.jpeg'
        }

I've just added '.jpeg' at the end of the name. I think it is depended on the backend programmer coding algorithm and It cannot cause problem always.