图片上传加预览

一个图片上传加预览的小demo,见笑了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
	<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<link rel="stylesheet" href="">
<style type="text/css" media="screen"media>
div{
width:64px;
height:64px;
border:1px solid #e0e0e0;
position:relative;
}


img,input{
width:inherit;
height:inherit;
position:absolute;
left:0;
top:0;
}


input{
opacity: 0;
z-index:999;
}

</style>

</head>
<body>
<div>
<input id="select_file" accept="image/*" name = 'file' type='file' />
<img src="" alt="">
</div>



<script type="text/javascript">
var img = document.querySelector('img'),
input = document.querySelector('#select_file');

input.onchange = function(ev){
var select_file = input.files[0];
// 图片预览
var reader = new FileReader();
reader.onload = function(e) {
img.src = e.target.result;
};
reader.readAsDataURL(select_file);

// 图片上传
var oMyForm = new FormData();
//创建一个formData,把图片加入到这个空的对象中
oMyForm.append('img',select_file);

var xhr;
if (window.XMLHttpRequest){
xhr=new XMLHttpRequest();
}else{
xhr=new ActiveXObject("Microsoft.XMLHTTP");
}

xhr.open(url,true);
xhr.send(oMyForm);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
console.log("upload complete");
console.log("response: " + xhr.responseText);
}
}
}
}

</script>

</body>
</html>

文章目录