使用js中的XMLHTTPREQUEST发送base64图像数据“POST”

时间:2013-06-29 05:24:19

标签: javascript html5 xmlhttprequest html5-canvas

我正在尝试将base64数据发布到服务器,但我收到一个错误“Microsoft JScript运行时错误:无法获取属性'addEventListener'的值:对象为null或未定义” 下面我附上了错误屏幕截图任何帮助谢谢。

            var imagefile = canvas.toDataURL("image/png");
            imagefile = imagefile.replace("data:image/png;base64,", "");
            var oXHR = new XMLHttpRequest();
            oXHR.upload.addEventListener('loadstart', uploadFinish, false);
            oXHR.upload.addEventListener('progress', uploadProgress, false);
            oXHR.upload.addEventListener('error', uploaderror, false);
            oXHR.open('POST',"http://demo.donelook.com/eyewearweb/levellens.aspx",true);
            oXHR.send(imagefile);

enter image description here

2 个答案:

答案 0 :(得分:0)

我想你想要:

oXHR.addEventListener('loadstart', uploadFinish, false);

答案 1 :(得分:0)

oXHR.upload.addEventListener中存在错误,应为oXHR.addEventListener。 另一个问题是所有浏览器都不支持addEventListener。如果您使用纯JavaScript,则必须执行此类操作。

if (!oXHR.addEventListener) {
    oXHR.attachEvent("loadstart", uploadFinish);
}
else {
    oXHR.addEventListener("loadstart", uploadFinish, false);
}

您可以将其作为单独的函数编写,并重复使用它以确保浏览器兼容性。像这样:

function addEventListener(element,type, listener, useCapture){
     if (!element.addEventListener) {
        element.attachEvent(type, listener);
     }
     else {
        element.addEventListener(type, listener, useCapture);
     }
}

您的代码:

var imagefile = canvas.toDataURL("image/png");
 imagefile = imagefile.replace("data:image/png;base64,", "");
 var oXHR = new XMLHttpRequest();
 addEventListener(oXHR,'loadstart', uploadFinish, false);
 addEventListener(oXHR,'progress', uploadProgress, false);
 addEventListener(oXHR,'error', uploaderror, false);
 oXHR.open('POST',"http://demo.donelook.com/eyewearweb/levellens.aspx",true);
 oXHR.send(imagefile);