Search code examples
phpreact-nativefile-uploadcodeigniter-4react-native-image-picker

Image upload issue with react-native and PHP(CodeIgniter) as backend


I have an app scenario with react native and CodeIgniter as backend.

I have a code snippet to upload image as picked by react-native-image-picker as below:

  let formData = new FormData();
  let imageBody = {
                uri: newImage,
                name: 'profilepicture.jpg',
                type: 'image/jpeg',
            };
formData.append('file', (imageBody)) // case 1 gives network error
formData.append('file', JSON.stringify(imageBody)) //case 2 goes OK

 apiUpdateUser(formData)
            .then(res => {

                this.setState({ showSnack: true, snackText: 'Profile Picture Updated'})
            })
            .catch(err => {
                this.setState({ showSnack: true, snackText: 'Update Failed' })
            });

The apiUpdateUser method goes as :

export const apiUpdateUser = body => {
return new Promise((resolve, reject) => {
    axios
        .post(ApiRoutes.updateUser, body, {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        })
        .then(res => {
            resolve(res.data);
        })
        .catch(err => {
            reject(Constant.network.networkError);
        });
});
};

The Php code at the backend to handle this upload as usual is:

$file=$this->request->getFile('file');//in CI
$file=$_FILES['file'];//in normal php

My issue is that I do not get anything whatsoever in the $file variabe with either of the methods, The file variable is empty in both the cases.

I've checked the implementation in react native and it doesnt seem to be buggy at all comparing with tutorials/demonstrations online. Also the way of handling at the backend is obvious and Ok.

I'm able to achieve this upload with POSTMAN easily but with react-native I'm facing this error. Can anyone show me some light here??


Solution

  • Turns out that the JSON.stringify() was the culprit line.

    Without that line, the app was giving out network error. That's why I had randomly added it just to see if that was the cause of error.

    Since, the network error issue was solved with that addition, I didn't give a second thought about it and only thought it to be a file upload issue. Actually, I now see that this is a known issue of a react native flipper version that I have been using which I managed to solve.