Search code examples
encodingfetchmultipartform-dataform-data

invalid byte sequence for encoding "UTF8": 0x00 response when i try to post and image with FormData object to the server


What I'm trying to do is simply update user's profile by sending new information. When i do that without sending a new image it works fine, but as soon as i attach new image to my FormData object server responses with this message:

message: "invalid byte sequence for encoding \"UTF8\": 0x00"

Here is my FormData:

const formData = new FormData();
formData.append('firstName', firstName);
formData.append('lastName', lastName);
formData.append('username', username);
formData.append('email', email);
formData.append('phoneNumber', phoneNumber);
formData.append('birthday', birthday);
formData.append('profileImage', profileImage);
dispatch(editProfile(formData, accessToken));

And here is my fetch function:

function editProfile({formData, accessToken}) {
    console.log(formData, 'hueta');
  const response = fetch('http://3.136.236.84/api/edit-profile/child/', {
    method: 'PUT',
    body: formData,
    headers: {
      'Authorization': `Bearer ${accessToken}`,
      'Content-type': 'application/json;charset=utf-8'
    },
  })
    .then(response => {console.log(response); return response.json()})
    .then(data => {
      return data;
    });
  return response;
}

My FormData

FormData {_parts: Array(7)}
_parts: Array(7)
0: (2) ["firstName", "Update"]
1: (2) ["lastName", "Child"]
2: (2) ["username", "1nspir3d"]
3: (2) ["email", "[email protected]"]
4: (2) ["phoneNumber", "+380981046865"]
5: (2) ["birthday", "28/04/2012"]
6: (2) ["profileImage", {…}]

My profileImage object

fileName: "9A5DDD17-3435-4E51-A048-51447D066708.png"
fileSize: 1388
height: 40
type: "image/png"
uri: "file:///Users/admin/Library/Developer/CoreSimulator/Devices/99D18B6D-9601-4F81-8EA4-9F0FCC287335/data/Containers/Data/Application/F4AFC648-04D3-4CB7-A475-4373C4DB6EB8/tmp/9A5DDD17-3435-4E51-A048-51447D066708.png"
width: 40
get fileName: ƒ ()
set fileName: ƒ ()
get fileSize: ƒ ()
set fileSize: ƒ ()
get height: ƒ ()
set height: ƒ ()
get type: ƒ ()
set type: ƒ ()
get uri: ƒ ()
set uri: ƒ ()
get width: ƒ ()
set width: ƒ ()

Is this problem related with my FormData or with server side?


Solution

  • So i found a solution which is quite simple. When you get an image from you're gallery using react-native-image-picker you will get an object with a few keys as a response. There is a 'uri' key which is different for IOS and Android. And for IOS you it looks like that:

    'file:///...'
    

    All you have to do is remove 'file://' and now i append my image like that:

    formData.append('profileImage', {
      name: profileImage.fileName,
      type: profileImage.type,
      uri: Platform.OS === 'android' ? 
           profileImage.uri :
           profileImage.uri.replace('file://', '')
    });
    

    In this article you can find more information about that.