如何通过内容类型为“image/jpeg”的 AJAX 调用将画布图像从 GUI 保存到后端

How to save a canvas image from GUI to back-end via AJAX call with content-type "image/jpeg"?

本文关键字:布图像 图像 后端 保存 GUI 调用 AJAX 类型 何通过 image jpeg      更新时间:2023-09-26

canvas如何通过AJAX接受content type "image/jpeg"克服错误" jquery.js:8453 Uncaught TypeError: Illegal invocation

.HTML

<canvas id="myImage"></canvas> // Canvas loaded with image

HTML

<canvas id="myImage"></canvas> // Canvas loaded with image

.JS

var can = $("#myImage");
var blob = this.dataURItoBlob(can.toDataURL("image/jpeg"));

var postPromise = $.ajax({
    type: "PUT",
    url: 'URL_to_save_the_image',//API URL to save image
    data: blob, //data should not be transformed to query string
    processData: false, // Important to overcome "jquery.js:8453 Uncaught TypeError: Illegal invocation" due to transformation to query string
    contentType: 'image/jpeg'
});
postPromise.done(function(data, textStatus, jqXHR) {
    //Success code goes here
});
postPromise.fail(function(jqXHR, textStatus, errorThrown) {
    //Failure code goes here
});
function dataURItoBlob(dataURI) {
    // convert base64/URLEncoded data component to raw binary data held in a string
    var byteString;
    if (dataURI.split(',')[0].indexOf('base64') >= 0)
        byteString = atob(dataURI.split(',')[1]);
    else
        byteString = unescape(dataURI.split(',')[1]);
    // separate out the mime component
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
    // write the bytes of the string to a typed array
    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
    });
}