一.css代碼css
給<input>標籤的父級設置一個‘+’背景圖,把<input type=file>的寬高設置得跟父級同樣,且徹底透明,html
這樣點擊的時候看似是點擊的‘+’的節點,其實點擊的是<input>節點。ajax
.file-box {
position: relative;
display: inline-block;
width:100px;
height:100px;
background:url('images/uploadPc.png')no-repeat;
background-size:100px 100px;
}
#input_file{
width:100%;
height:100%;
opacity: 0;
filter:alpha(opacity=0);
}json
二.html代碼app
<div class="file-box">
<input type="file" value="" name="file" id = "input_file"
accept="image/gif,image/jpeg,image/jpg,image/png,image/svg" οnchange="imgPreview(this,0)" >
</div>async
三.js代碼svg
//這個方法是給$("#input_file")這個對象設置圖片的值並回顯圖片post
function imgPreview(fileDom,i) {
var reader = new FileReader();
var file = fileDom.files[0];
var imageType = /^image\//;
if(!imageType.test(file.type)) {
alert("請選擇圖片!");
return;
}this
reader.readAsDataURL(file);
reader.onload = function(e) {
console.log(document.getElementsByClassName('file-box'));
$('.file-box').css({"background":"url("+this.result+") no-repeat","backgroundSize":"200px 160px"});//回顯
};
}
上傳部分的代碼:url
var formData = new FormData(); formData.append('photo', $('#input_file')[0].files[0]); $.ajax({ type: "post", url: "uploadaddress", data: formdata, dataType: 'json', processData: false, // 告訴jQuery不要去處理髮送的數據 contentType: false, // 告訴jQuery不要去設置Content-Type請求頭 xhrFields:{withCredentials:true}, async: true, success: function (data) { callback(data); } });