Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload image from data url to Axios?

Ive been uploading image files to an API (Graphcool) with this, and everything was working fine:

fileUpload(file) {
        let data = new FormData();
        data.append('data', file);

        axios
            .post(`https://api.graph.cool/file/v1/MY-PROJECTID`, data, {
                headers: {
                    'Content-Type': 'multipart/form-data',
                },
            })
            .then(res => {
                console.log(res)
            });
    }

In the code above the file was passed from a <input type="file" />

However now I'm using React Avatar Editor to allow users to crop images and ensure they are a square: https://github.com/mosch/react-avatar-editor

When you access the image from React Avatar Editor it comes in the form of a data url (via Canvas.toDataURL()).

How can I upload a data url with Axios? Do I need to first convert the image to an actual 'file' in the browsers memory?

like image 464
Evanss Avatar asked Mar 12 '18 04:03

Evanss


1 Answers

This is a duplicate of below thread just in a different language

Sending canvas.toDataURL() as FormData

You need to change your code like below

    function fileUpload(canvas) {
        let data = new FormData();
        canvas.toBlob(function (blob) {
            data.append('data', blob);
    
            axios
                .post(`https://api.graph.cool/file/v1/MY-PROJECTID`, data, {
                    headers: {
                        'Content-Type': 'multipart/form-data',
                    },
                })
                .then(res => {
                    console.log(res)
                });
        });
    }
like image 97
Tarun Lalwani Avatar answered Nov 10 '22 05:11

Tarun Lalwani