一.html頁面保留按鈕和隱藏的img標籤
<div>
選擇圖片:
<input type="file" id="file" name="file" capture="camera" accept="image/jpeg,image/png,image/jpeg,image/gif">
<div id="result" align="center">
<div id="imgDiv" style="display: none;">
<img id="img" style="height: 300px;width: 250px;margin-left: 10%;"/>
</div>
</div>
</div>
二.jquery設置file改變函數
$("#file").change(function(event){
var files = event.target.files, file;
if (files && files.length > 0) {
// 獲取目前上傳的文件
file = files[0];// 文件大小校驗的動作
if(file.size > 1024 * 1024 * 2) {
alert('圖片大小不能超過 2MB!');
return false;
}
// 獲取 window 的 URL 工具
var URL = window.URL || window.webkitURL;
// 通過 file 生成目標 url 獲取真實的路徑
var imgURL = URL.createObjectURL(file);
//用attr將img的src屬性改成獲得的url
$("#img").attr("src",imgURL);
$("#imgDiv").show();
// 使用下面這句可以在內存中釋放對此 url 的伺服,跑了之後那個 URL 就無效了
// URL.revokeObjectURL(imgURL);
}
});
三.測試