h5可预览 图片ajax上传 ,后台有点弱不知道数据怎么取,但是可以肯定数据上传成功了

时间:2021-04-27 08:51:14
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
.box{
height: 200px;
width: 600px;
border: 1px solid black;
margin: 100px auto;
}
.demo img{
height: 100px;
width: 100px;
border: 5px solid #CCCCCC;
}
</style>
</head>
<body>
<div class="box">
<input type="file" name="" id="btn" value="文件上传" multiple="multiple" />
<input type="button" id="btn1" value="ajax提交到服务器" />
<div class="demo"></div>
</div>
<script src="hezhifile.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript"> //存储所有文件的预览信息
var sumfile = [];
//控件上传
var btn = document.getElementById("btn"); btn.onchange = function(){
var ffs = []
for (var i=0;i<this.files.length;i++) {
ffs[i] = this.files[i]
}
sumfile = sumfile.concat(ffs)
//过滤文件
//var ffs = fileFilter(ffs);
//读取文件 for (var i=0;i<ffs.length;i++) {
(function(i){
var freader = new FileReader(); freader.readAsDataURL(ffs[i],'gbk') freader.onload = function(){
var result = freader.result;
var img = document.createElement('img');
img.src = result;
document.querySelector('.demo').appendChild(img)
} })(i)
} this.value= "";//用自定义按钮来做,原生的太丑了
console.log(sumfile);
} //过滤文件的函数
function fileFilter(files){
for(var i=0;i<files.length;i++){
if(files[i].size>5000){
alert(files[i].name+'该图片大于5000,上传失败')
files.splice(i,1)
}
} return files
} //拖拽上传
var obox = document.querySelector('.box'); obox.ondragover = function(ev){
var ev = ev || event;
ev.preventDefault()
ev.stopPropagation()
}
obox.ondrop = function(ev){
var ev = ev || event;
ev.preventDefault();
var ffs = []
for (var i= 0;i < ev.dataTransfer.files.length;i++) {
ffs[i] = ev.dataTransfer.files[i]
} //一个拖动多上上传
sumfile = sumfile.concat(ffs); var freader = new FileReader(); freader.readAsDataURL(ffs[0],'gbk') freader.onload = function(){
var result = freader.result;
var img = document.createElement('img');
img.src = result;
document.querySelector('.demo').appendChild(img)
} console.log(sumfile);
} //ajax 上传
var btn1 = document.querySelector('#btn1'); btn1.onclick = function(){ for(var i=0;i< sumfile.length;i++){
(function(i){
var formData = new FormData(); //formData.append('name',sumfile[i].name)
formData.append("userfile", sumfile[i]); var xhr = new XMLHttpRequest(); xhr.open('post','01.php',true)
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); xhr.send(formData) xhr.onreadystatechange= function(){
if(xhr.readyState==4&&xhr.status==200){
var result = xhr.responseText;
document.body.innerHTML+=result
}
} })(i)
} //取出每个文件一个个上传 } </script> </body>
</html>