出现xhr.sendasbinary is not a function错误

在使用ajax上传文件的时候,会出现

xhr.sendasbinary is not a function错误

进入到xhr.js里面看,果然没有这个方法

修改前的代码如下所示

function uploadAndSubmit(){
	 var form = document.forms["demoForm"]; 
	 if (form["file"].files.length > 0) { 
	 // 寻找表单域中的 <input type="file" ... /> 标签
	 var file = form["file"].files[0]; 
	 // try sending 
	 var reader = new FileReader(); 

	 reader.onloadstart = function() { 
	 // 这个事件在读取开始时触发
	 console.log("onloadstart"); 
	 document.getElementById("bytesTotal").textContent = file.size; 
	 }; 
	 reader.onprogress = function(p) { 
	 // 这个事件在读取进行中定时触发
	 console.log("onprogress"); 
	 document.getElementById("bytesRead").textContent = p.loaded; 
	 } ;

	 reader.onload = function() { 
	    // 这个事件在读取成功结束后触发
	 console.log("load complete"); 
	 } ;

	 reader.onloadend = function() { 
	    // 这个事件在读取结束后,无论成功或者失败都会触发
		 if (reader.error) { 
		 console.log(reader.error); 
		 } else { 
			 document.getElementById("bytesRead").textContent = file.size; 
			 // 构造 XMLHttpRequest 对象,发送文件 Binary 数据
			 var xhr = new XMLHttpRequest(); 
			 xhr.open(/* method */ "POST", 
			 /* target url */ "upload.jsp?fileName=" + file.name 
			 /*, async, default to true */); 
			 xhr.overrideMimeType("application/octet-stream"); 
			 xhr.sendAsBinary(reader.result); 
			 xhr.onreadystatechange = function() { 
				 if (xhr.readyState == 4) { 
					 if (xhr.status == 200) { 
						 console.log("upload complete"); 
						 console.log("response: " + xhr.responseText); 
					 } 
				 } 
			 } ;
		 } 
	 } ;
	 
	 reader.readAsBinaryString(file); 
	 } else { 
		 alert ("Please choose a file."); 
	 	} 
	 }
这里手工加上下面这段代码即可

 if(!XMLHttpRequest.prototype.sendAsBinary){
		  XMLHttpRequest.prototype.sendAsBinary = function(datastr) {
		    function byteValue(x) {
		      return x.charCodeAt(0) & 0xff;
		    }
		    var ords = Array.prototype.map.call(datastr, byteValue);
		    var ui8a = new Uint8Array(ords);
		    this.send(ui8a.buffer);
		  };
		} 
然后就可以成功传到conrtoller辣

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值