In order to take photos of the use of webcam-related plug-ins, its shooting is the base64 format of the picture, direct display no problem, in the SRC directly specified on it, but to upload to the server when the problem comes, the server side receives the standard file, that is, HTML The form type= "file". To follow this interface without changing the server-side code, you try to convert base64 directly to the standard Fomedata and submit it via Ajax.
The first step is to convert the Base64 into a binary picture (BLOB)
The main idea is to tidy up the first few characters of the Base64, after preprocessing to convert to BLOB objects, which can be slightly processed after the formdata.
function Datauritoblob (base64data) {
var bytestring;
if (Base64data.split (', ') [0].indexof (' base64 ') >= 0)
bytestring = Atob (Base64data.split (', ') [1]);
else
bytestring = unescape (Base64data.split (', ') [1]);
var mimestring = Base64data.split (', ') [0].split (': ') [1].split (';') [0];
var ia = new Uint8array (bytestring.length);
for (var i = 0; i < bytestring.length i++) {
Ia[i] = bytestring.charcodeat (i);
}
return new Blob ([ia], {type:mimestring});
}
The second step is to build formdata
We need to use HTML5 's canvas.
var blob = Datauritoblob (imageBase64); The function in the previous step
var canvas = document.createelement (' canvas ');
var dataurl = Canvas.todataurl (' image/jpeg ', 0.5);
var fd = new FormData (document.forms[0]);
Fd.append ("The_file", blob, ' image.png ');
The above the_file for this file key, is equivalent to the input name,image.png is the file name, because Base64 picture information is not with the filename, so you can manually specify a, this parameter is optional
Step three, use Ajax to submit
For convenience, here we use jquery Ajax to demonstrate that we have built a formdata called FD, which can be submitted directly
$.ajax ({
URL: ' http://www.example.com/upload ', method
: ' POST ',
processdata:false,//Must
Contenttype:false,//Must be
dataType: ' json ',
DATA:FD,
success (data) {
console.log (data);
}
});
The above is a small series to introduce the JavaScript will base64 picture into formdata and through the implementation of Ajax submission, hope to help everyone, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!