form表單+jquery上傳圖片


html代碼

<form method="get" id="upload-form" class="upload-form" enctype ="multipart/form-data">
<div id="uploadChecks"><p class="uploadTip">點擊上傳</p></div>
<input id="upload-inp" style="display: none" type="file">
</form>

css代碼

<style>
*{
margin: 0px;
padding: 0px;
}
#uploadChecks{
width: 100px;
height: 100px;
background: #ccc;
position: relative;
}
.uploadTip{
position: absolute;
top: 0px;
right: 0px;
bottom: 0px;
left: 0px;
background: rgba(0,0,0,0.2);
color: #fff;
font-size: 13px;
line-height: 100px;
text-align: center;
display: none;
}
</style>

js代碼

<script>
$("#uploadChecks").mouseover(function(){
$(".uploadTip").show();
}).mouseleave(function(){
$(".uploadTip").hide();
})
//上傳
$("#uploadChecks").click(function () {
$("#upload-inp").click();
$("#upload-inp").on("change",function(e){
//獲取圖片的路徑,並顯示出來
var objUrl = getObjectURL(this.files[0]);
if (objUrl) {
$("#uploadChecks").css({
"background":"url("+objUrl+")",
"background-size":"cover"
})
}
//獲取上傳圖片包
var formdata = new FormData()// FormData對象,來發送二進制文件。
formdata.append("file",e.currentTarget.files[0]);// 將文件追加到 formdata對象中
$.ajax({
url:'',//上傳接口
type:'POST',
data:formdata,
processData: false,//必須false才會避開jQuery對 formdata 的默認處理, XMLHttpRequest會對 formdata 進行正確的處理
contentType: false,// 告訴jQuery不要去設置Content-Type請求頭
success:function(res){
console.log(res)
},
error: function (res) {
console.log("發生錯誤")
}
})
})
});
//建立一個可存取到該file的url
function getObjectURL(file) {
var url = null ;
if (window.createObjectURL!=undefined) { // basic
url = window.createObjectURL(file) ;
} else if (window.URL!=undefined) { // mozilla(firefox)
url = window.URL.createObjectURL(file) ;
} else if (window.webkitURL!=undefined) { // webkit or chrome
url = window.webkitURL.createObjectURL(file) ;
}
return url ;
}
</script>
 
       


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM