javascriptnode.jsbase64image-filebackblaze

File format not supported but when decoding it with base64 it works fine


Hello i'm having issue with uploading image to the cloud (Backblaze B2).

The problem is, when I use the example Thunder client to upload the file everything works fine and file is shown.

Now my problem is that when I upload with JS I don't know why it is corrupted or bugged. Like when I upload an image and download it, Windows File Manager says : file format not supported.

I decoded the file with base64 img decoder and it works fine and image is shown.

const submitForm = () => {
        var reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function(e) {
            // binary data
            let imagedata = reader.result.slice(reader.result.indexOf(',') + 1)

            console.log(imagedata);

            console.log(sha1(imagedata));
            const proxyurl = "https://cors-anywhere.herokuapp.com/";

            let datadf = fetch(proxyurl + 'url', {
                    method: 'POST',
                    headers: {
                        "Accept": "*/*",
                        "User-Agent": "Thunder Client (https://www.thunderclient.io)",
                        "X-Bz-File-Name": file.name,
                        "X-Bz-Content-Sha1": "do_not_verify",
                        "Authorization": "auth",
                        "Content-Type": "b2/x-auto",

                    },
                    body: imagedata,
                })
                .then((response) => {

                    return response.json();
                })
                .catch((err) => {
                    return {
                        status: 'fail',
                        message: 'API CALL ERROR',
                        error: err.message
                    };
                });
            datadf.then(res => console.log(res))
        };
        reader.onerror = function(e) {
            // error occurred
            console.log('Error : ' + e.type);
        };

Solution

  • .readAsDataURL() converts the file it reads into Base64, so it can be represented as a URL you can put into a browser. A very long URL, but still a URL.

    If you store a Base 64 representation of an image into a file on your machine, then try to read it with an image-display program, the operation will fail: "This doesn't look like a .jpg, .png, or .gif" so I don't know what to do with it." That's what your Windows file manager error message means.

    If you want the file's contents raw rather than Base64 encoded, you'll need to use .readAsArrayBuffer().