rozina
rozina

Reputation: 53

converting image to base64 - image becomes invisible

I'm trying encode an image to base64, (so I can later send it this way to a backend server). Everything seems to work until I use JSON.stringify() on the object that has the encoded image in it. I think It gets lost in the JSON.stringify() and I can't seem to find a solution. I've been working for weeks on this issue and I couldn't find an answer anywhere. Please help!

 const [baseImage, setBaseImage] = useState('');
 const [baseImageCorrect, setBaseImageCorrect] = useState('');

const convertBase64 = (file) => {
        return new Promise((resolve, reject) => {
            const fileReader = new FileReader();
            fileReader.readAsDataURL(file);

            fileReader.onload = () => {
                resolve(fileReader.result);
            };

            fileReader.onerror = (error) => {
                reject(error);
                console.log(error);
            };
        });
    };

 const uploadImage = async (e) => {
        const file = e.target.files[0];
        const base64 = await convertBase64(file);
        const base64RemovedType = base64.split(',')[1];
        setBaseImage(`${base64RemovedType}`);
    };

    useEffect(() => {
        setBaseImageCorrect(baseImage);
        console.log('current:' + baseImageCorrect);
//prints out a long string with the RIGHT information
    }, [baseImage, baseImageCorrect]);

    
 const EncodedImage = JSON.stringify({
            fileBase64: (baseImageCorrect, { encoding: 'base64' }),
        });

        console.log(EncodedImage)
//PRINTS THIS: "fileBase64":{"encoding":"base64"}} , without the encoded image string

Upvotes: 0

Views: 949

Answers (1)

alpheus
alpheus

Reputation: 240

I am assuming u need the key baseImageCorrect and encoding key at the same level.

Use this instead:

const EncodedImage = JSON.stringify({
            fileBase64: {baseImageCorrect, encoding: 'base64' },
        });

Upvotes: 1

Related Questions