使用jQuery在上传图片之前实现缩略图预览
jQuery代码
01 |
$("#uploadImage").on("change", function(){
|
02 |
// Get a reference to the fileList
|
03 |
var files = !!this.files ? this.files : [];
|
04 |
|
05 |
// If no files were selected, or no FileReader support, return
|
06 |
if (!files.length || !window.FileReader) return;
|
07 |
|
08 |
// Only proceed if the selected file is an image
|
09 |
if (/^image/.test( files[0].type)){
|
10 |
|
11 |
// Create a new instance of the FileReader
|
12 |
var reader = new FileReader();
|
13 |
|
14 |
// Read the local file as a DataURL
|
15 |
reader.readAsDataURL(files[0]);
|
16 |
|
17 |
// When loaded, set image data as background of div
|
18 |
reader.onloadend = function(){
|
19 |
|
20 |
$("#uploadPreview").css("background-image", "url("+this.result+")");
|
21 |
|
22 |
}
|
23 |
|
24 |
}
|
25 |
|
26 |
}); |
以下是HTML代码,包含一个显示缩略图的div和一个file input field。
HTML代码
1 |
<div id="uploadPreview"></div>
|
2 |
<input id="uploadImage" type="file" name="photoimage" class="fimg1" onchange="PreviewImage();" />
|
为我们的缩略图设置CSSwa 。
CSS代码
1 |
<strong>#uploadPreview { |
2 |
width: 168px;
|
3 |
height: 168px;
|
4 |
background-position: center center;
|
5 |
background-size: cover;
|
6 |
border: 4px solid #fff;
|
7 |
-webkit-box-shadow: 0 0 1px 1px rgba(0, 0, 0, .3);
|
8 |
display: inline-block;</strong>
|