Upload image from data url to Axios?
Asked Answered
P

1

7

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?

Pagepageant answered 12/3, 2018 at 4:20 Comment(2)
You can convert dataURI to a blob - https://mcmap.net/q/41998/-blob-from-dataurlPolyvalent
@Evans, any update on this?Villenage
V
6

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)
                });
        });
    }
Villenage answered 20/3, 2018 at 11:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.