how to convert canvas to image to upload to flask?

Viewed 3446

Alright so I'm trying to upload a resized canvas image as a file to Flask.

First I tried to use the canvas.toDataURL() to convert it to a base64(?) string then tried to upload that as an image using formdata with AJAX, no luck.

Then I tried converting the base64 to a blob using this function:

    function toblob(stuff) {
    var g, type, bi, ab, ua, b, i;
    g = stuff.split(',');
    if (g[0].split('png')[1])
        type = 'png';
    else if (g[0].split('jpeg')[1])
        type = 'jpeg';
    else
        return false;
    bi = atob(g[1]);
    ab = new ArrayBuffer(bi.length);
    ua = new Uint8Array(ab);
    for (i = 0; i < bi.length; i++) {
        ua[i] = bi.charCodeAt(i);
    }
    b = new Blob([ua], {
        type: "image/" + type
    });
    return b;
}

not image...

here's the ajax form I used:

s = new FormData();
s.append('image', toblob(d)); \\I believe I refer to this with request.files['image']?
var g = $.ajax({
    url: 'url', 
    type: 'POST',
    processData : false,
    contentType : false, 
    data: s
}) //POSTDATA

Heres what I have so far serverside:

@app.route('/requests/<req>', methods=['POST'])
def requests(req=None): 
        if req == 'upload' and request.method == 'POST' and request.files['file']:
    file = request.files['image'] \\referring to formdata() key
    if file and allowed_file(file.filename):
        n = secure_filename(file.filename)
        file.save(os.path.join(app.config['UPLOAD_FOLDER'],n))
        return redirect(url_for('index', p=n))

ALL THAT ASIDE AND MORE IMPORTANTLY

I feel pretty confident that the javascript is doing a good job of sending the data as many other stackoverflow questions use the same method for PHP servers and the server is indeed recieving the data.

My problem is that I don't know how to convert this data into a physical file to store into a directory?

  • I've tried using the upload tutorial but the data isn't a file so that doesn't work.
  • I found one tutorial on how to upload blobs (I think?) but it doesn't work because it uses "files" which isn't defined.

Is there any way I can convert this data into physical image file through flask or js?

THANKYOU!

1 Answers
Related