xhr文件上传
由于项目需要上传大文件(我用的是PHP),但是当文件查过4G之后就会上传失败。调整php.ini配置依然无法解决。
因为用.net写依然无法上传超过4G的文件,所以猜测应该是Form表单上传的限制。
后来了解到xhr上传,完美解决大文件上传问题。
html 页面代码
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<title>大文件上传</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style>
#upimg{
text-align: center;
font: 8px/10px '微软雅黑','黑体',sans-serif;
width: 300px;
height: 10px;
border: 1px solid green;
display: inline-block;
}
#load{
width: 0%;
height: 100%;
background: green;
text-align: center;
}
.clickUp{
background: #BDBDBD;
border: 1px solid #99D3F5;
border-radius: 4px;
padding: 4px 12px;
overflow: hidden;
/*color: #1E88C7;*/
text-decoration: none;
text-indent: 0;
line-height: 20px;
}
.clickUp:hover{
background: #AADFFD;
border-color: #78C3F3;
color: #004974;
text-decoration: none;
}
</style>
</head>
<body>
<form enctype="multipart/form-data" action="" method="post">
<div id="upimg">
<div id="load"></div>
</div>
<input type="file" name="mof" multiple="multiple"/><br>
<input type="button" class="clickUp" value="点击上传" onclick="upFile();" />
</form>
JS 代码
var dom=document.getElementsByTagName('form')[0];
dom.onsubmit=function(){
//return false;
};
var xhr=new XMLHttpRequest();
var fd;
var des=document.getElementById('load');
//var num=document.getElementById('upimg');
var file;
//文件大小
const LENGTH = 1024 * 1024 * 15360;
var start;
var end;
var blob;
var pecent;
function upFile(){
start=0;
end=LENGTH+start;
file=document.getElementsByName('mof')[0].files[0];
if(!file){
alert('请选择文件!');
return;
}
up();
}
function up(){
if(start<file.size){
xhr.open('POST','后台处理地址',true);
xhr.onreadystatechange=function(){
if(this.readyState==4){
if(this.status>=200&&this.status<300){
if(this.responseText.indexOf('failed') >= 0){
top.postMessage(xhr.responseText, 'http://xxxx/');
des.style.width='0%';
}else{
start=end;
end=start+LENGTH;
setTimeout('up()',1000);
var code = JSON.parse(xhr.responseText).code;
console.log(JSON.parse(xhr.responseText));
console.log(code);
if(code == 1){
top.postMessage(xhr.responseText, 'http://xxxx/')
}
}
}
}
};
xhr.upload.onprogress=function(ev){
if(ev.lengthComputable){
pecent=100*(ev.loaded+start)/file.size;
if(pecent>100){
pecent=100;
}
des.style.width=pecent+'%';
des.innerHTML = parseInt(pecent)+'%';
}
};
//分割文件核心部分slice
blob=file.slice(start,end);
fd=new FormData();
fd.append('mof',blob);
fd.append('test',file.name);
xhr.send(fd);
}else{
//clearInterval(clock);
}
}