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?
Is there any way I can convert this data into physical image file through flask or js?
THANKYOU!
Found a work-around!
instead of using Flask's file.save()
, I used werkzeug's FileStorage()
Which (as far as I know) a raw version of the file.save()
I used it by specifying the filename
and stream
(which is a blob FYI) like so:
FileStorage(stream=request.files['image']).save(os.path.join(app.config['AUTHOR_FOLDER'],'testpic.jpg')))
Plopped it down into the script, dodged around the error 400s and barely scrapped together a working function! haha.
It works but I have no idea how secure it is or how stable it is, just going to go with it for now. If any one has any experience please help me out. Thanks!
Life is awesome!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With