DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content=">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Documenttitle>
<style>
.a-upload {
padding: 4px 10px;
height: 20px;
line-height: 20px;
position: relative;
cursor: pointer;
color: #888;
background: #fafafa;
border: 1px solid #ddd;
border-radius: 4px;
overflow: hidden;
display: inline-block;
*display: inline;
*zoom: 1
}
.a-upload input {
position: absolute;
font-size: 100px;
right: 0;
top: 0;
opacity: 0;
filter: alpha(opacity=0);
cursor: pointer
}
.a-upload:hover {
color: #444;
background: #eee;
border-color: #ccc;
text-decoration: none
}
.test{
width: 100px;
height: 100px;
background:rgba(0,0,0,0.2); filter: progid:DXImageTransform.Microsoft.gradient(startcolorstr=#7F000000,endcolorstr=#7F000000);
}
.upload{
width: 100px;
height: 40px;
padding: 5px 10px;
position: relative;
overflow: hidden;
background: red;
cursor: pointer;
border-radius: 5px;
line-height: 40px;
text-align: center;
}
.upload:hover{
background: firebrick;
}
.upload input{
font-size: 200px;
position: absolute;
opacity: 0;
-ms-filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=0);
filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=0);
top: 0;
right: 0;
cursor: pointer;
}
style>
head>
<body>
<div class="test">
豆腐干豆腐
div>
<div class="a-upload">
<input type="file" name="" id="">点击这里上传文件
div>
<div class="upload">
<input type="file" id="img" multiple>
上传图片
div>
<div id="imgBox">
div>
body>
<script>
var imgEle=document.getElementById("img");
var arr=[];
imgEle.addEventListener("change",function (e) {
// 获取文件列表对象
var files = e.target.files || e.dataTransfer.files;
for (var i = 0, file; file = files[i]; i++) {
if (file.type.indexOf("image") == 0) {
if (file.size >= 512000) {
alert('您这张"'+ file.name +'"图片大小过大,应小于500k');
} else {
var reader = new FileReader();
reader.onload = function(e) {
var imgB=document.getElementById("imgBox");
var imgEle=document.createElement("img");
imgEle.setAttribute("src",e.target.result);
imgB.appendChild(imgEle);
};
reader.readAsDataURL(file);
arr.push(file);
}
} else {
alert('文件"' + file.name + '"不是图片。');
}
}
console.log(arr);
})
// 上传
var xhr = new XMLHttpRequest();
// 文件上传成功或是失败
xhr.onreadystatechange = function(e) {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
// 成功
}
} else {
// 失败
}
}
};
// 开始上传
xhr.open("POST", url, true);
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
var fd = new FormData();
fd.append("myPhoto", files[0]);
//执行发送
xhr.send(fd);
script>
html>