jquery完整的前端上傳圖片功能(帶自定義圖片預覽效果驗證尺寸大小驗證圖片格式)
阿新 • • 發佈:2020-12-23
技術標籤:工作分享jshtmljqueryjavascriptcss
最近經常遇到前端開發時,需要進行自定義圖片上傳的功能,因此自己在網上找了很多模板,拼接組合一下,寫了一個可以直接利用jquery使用的模板,可以直接拿走進行改裝,直接上程式碼。程式碼中有相應的註釋
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content=" width=device-width, initial-scale=1.0">
<title>jquery圖片上傳功能和圖片預覽效果(包含大小型別驗證效果)</title>
</head>
<body>
<div class="upload-img-box">
<div class="input-box">
<input type="file" id="img-file" name="選擇圖片">
</div>
<div class="befor-img">
<span>+ 請新增圖片</span>
</div>
<div class="after-img">
<img id="img-box" src="" width="100%" height=" 100%">
</div>
</div>
</body>
<style>
.upload-img-box {
position: relative;
}
.upload-img-box .input-box {
display: inline-block;
width: 300px;
height: 90px;
border: solid black 1px;
}
.upload-img-box .befor-img {
display: flex;
width: 300px;
height: 90px;
border: solid black 1px;
position: absolute;
top: 0px;
left: 0px;
background: #ffffff;
z-index: 30;
align-items: center;
justify-content: center;
}
.upload-img-box .befor-img.hasImg {
display: none;
}
.upload-img-box .after-img {
display: inline-block;
width: 300px;
height: 90px;
border: solid black 1px;
position: absolute;
top: 0px;
left: 0px;
background: #ffffff;
z-index: 20;
}
</style>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
<script>
//使用trggier事件,利用假的標籤觸發input[type=file]的標籤,從而進行自定義ui;
$(document).on("click", ".upload-img-box .befor-img,.upload-img-box .after-img", function (e) {
$(".input-box input").trigger("click");
})
// 使用input 的change事件,監聽當檔案上傳的值進行改變的時候,才觸發事件。
$(document).on("change", ".upload-img-box #img-file", function () {
var file = $("#img-file")[0].files[0];
console.log(file);
// file 內容包括: lastModified , lastModifiedDate , name , size , type
var formdata = new FormData();
formdata.append('file', file);
if (window.FileReader) {
var fr = new FileReader();
fr.onloadend = function (e) {
// console.log(this.result);
// document.getElementById("portrait").src = e.target.result;
$("#img-box").attr("src",e.target.result)
$(".upload-img-box .befor-img").addClass("hasImg")
};
//給FileReader物件一個讀取完成的方法,
//使用readAsDataURL會返回一個url
//這個值就儲存在事件物件的result裡
//img通過載入這個地址,完成圖片的載入
fr.readAsDataURL(file);
}
//判斷圖片大小
if (file.size > 3 * 1024 * 1024) {
alert("上傳圖片不能大於3M");
}
//判斷圖片資料型別
if (!/.(gif|jpg|jpeg|png|GIF|JPG|bmp)$/.test(file.name)) {
alert("圖片型別必須是.gif,jpeg,jpg,png,bmp中的一種");
}
})
</script>
</html>
效果圖
上傳圖片後
歡迎大家進行交流補充,謝謝。