抄自
http://blog.csdn.net/qiulei_21/article/details/52785191
第一種方法比較好
版權聲明:本文為博主原創文章,未經博主允許不得轉載。
根據項目需要,需要選擇本地圖片並顯示在頁面上,然后上傳至服務器。因為自身剛剛接觸js,所以比較生疏,碰到問題吼,幸好有強大的網絡,搜索很多有用的資源,現在將js讀取本地圖片並顯示的代碼總結一下,供大家使用,並給自己一個記錄。
第一種方法:
<script type="text/JavaScript">
//圖片顯示插件
(function ($) {
$.imageFileVisible = function (options) {
// 默認選項
var defaults = {
//包裹圖片的元素
wrapSelector: null,
//<input type=file />元素
fileSelector: null,
width: '100%',
height: 'auto',
errorMessage: "不是圖片"
};
// Extend our default options with those provided.
var opts = $.extend(defaults, options);
$(opts.fileSelector).on("change", function () {
var file = this.files[0];
var imageType = /image.*/;
if (file.type.match(imageType)) {
var reader = new FileReader();
reader.onload = function () {
var img = new Image();
img.src = reader.result;
$(img).width(opts.width);
$(img).height(opts.height);
$(opts.wrapSelector).append(img);
};
reader.readAsDataURL(file);
} else {
alert(opts.errorMessage);
}
});
};
})(jQuery);
$(document).ready(function () {
//圖片顯示插件
$.imageFileVisible({ wrapSelector: "#image-wrap1",
fileSelector: "#file1",
width: 300,
height: 300
});
$.imageFileVisible({ wrapSelector: "#image-wrap2",
fileSelector: "#file2",
width: 300,
height: 300
});
});
</script>
<div id="ImportHead">
<table border="0" class="frm" style="height: 35px; width: auto; padding-left: 5px;
padding-top: 1px;">
<tr style="width: 300px; height: 400px;">
<th>
選擇圖1:
</th>
<td>
<input type="file" id="file1">
<div id="image-wrap1" style="width: 300px; height: 300px; border: solid 1px lightGray">
</div>
</td>
<th>
選擇圖2:
</th>
<td style="width: 300px;">
<input type="file" id="file2">
<div id="image-wrap2" style="width: 300px; height: 300px; border: solid 1px lightGray">
</div>
</td>
</tr>
<tr>
<td colspan="2" style="text-align: right">
<input type="submit" id="btnUpload" class="btnSearch" value="上傳" />
</td>
</tr>
</table>
</div>
第二種方法:
<html>
<body>
<img id="image"src=""/>
<br/>
<input type="file"onchange="selectImage(this);"/>
<br/>
<script>
var image = '';
function selectImage(file) {
if (!file.files || !file.files[0]) {
return;
}
var reader = new FileReader();
reader.onload = function (evt) {
document.getElementById('image').src = evt.target.result;
image = evt.target.result;
}
reader.readAsDataURL(file.files[0]);
}
</script>
</body>
</html>
