且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Ajax POST请求将图像和JSON数据发送到服务器?

更新时间:2023-01-01 16:42:50

我遇到的常见方法是使用Base64字符串方法:将图像编码为Base64字符串并将其设置为部分您发送到服务器的JSON对象。

The common ways I encountered are using the Base64 string approach: you encode your image into a Base64 string and set it as part of the JSON Object that you send over to your server.

另一种方法似乎是在JSON中使用二进制数据,但我之前从未尝试过这么多信息来自我。

Another approach seems to be using the Binary Data in JSON but I'd never tried this before so not much info from me.

这里是代码示例在Javascript中进行Base64编码。具体来看下面的方法

Here's a code sample to do a Base64 encoding in Javascript. Specifically look for the method below

function getBase64Image(imgElem) {
// imgElem must be on the same server otherwise a cross-origin error will be thrown "SECURITY_ERR: DOM Exception 18"
    var canvas = document.createElement("canvas");
    canvas.width = imgElem.clientWidth;
    canvas.height = imgElem.clientHeight;
    var ctx = canvas.getContext("2d");
    ctx.drawImage(imgElem, 0, 0);
    var dataURL = canvas.toDataURL("image/png");
    return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}