Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FormData in React Native throws blank object

In my React Native project i'm using react-native-image-picker for image upload. Here, i am using formData to upload image. Image URL is there, but when i console the formData it shows {}. I don't know why this is happening. Here's the code :

    uploadImageAsync = async (imgUri, token) => {

        let apiUrl = 'url';
        let formData = new FormData();

        let uriParts = imgUri.split('.');
        let fileType = uriParts[uriParts.length - 1];

        //generate some random number for the filename
        var randNumber1 = Math.floor(Math.random() * 100);
        var randNumber2 = Math.floor(Math.random() * 100);

         formData.append('image', {
            uri: imgUri,
            name: `photo-${randNumber1}-${randNumber2}.${fileType}`,
            type: `image/${fileType}`,
         });

        console.log('formData :', formData);

        let options = {
            method: 'POST',
            body: formData,
            headers: {
                Accept: 'application/json',
                Authorization: 'Bearer ' + token,
                'Content-Type': 'multipart/form-data',
                'Cache-Control': 'no-cache',
            },
        };

        const response = await fetch(apiUrl, options);
        const json = await response.json();
 
    }
    };

Console of formData shows no data but imgUri consists image path. Why formData is showing no data?

like image 791
Tanmoy Sarker Avatar asked Jun 17 '26 21:06

Tanmoy Sarker


1 Answers

The value property of FormData.append() can be either a USVString or a Blob. Therefore, you can try stringifying your object and then optionally parse the string data.

const imageData = {
    uri: imgUri,
    name: `photo-${randNumber1}-${randNumber2}.${fileType}`,
    type: `image/${fileType}`,
};

const formData = new FormData();
formData.append("image", JSON.stringify(imageData));

const formImageData = formData.get("image");
const parsedFormImageData = JSON.parse(formImageData);

console.log(parsedFormImageData );
like image 193
Chunky Chunk Avatar answered Jun 20 '26 10:06

Chunky Chunk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!