1、html
<img id="pic" src="http://www.jq22.com/tx/28.png">
<input id="upload" name="file" accept="image/*" type="file" style="display: none">
2、jq
$(function() {
$("#pic").click(function() {
$("#upload").click(); //隱藏了input:file樣式後,點擊頭像就可以本地上傳
$("#upload").on("change", function() {
var objUrl = getObjectURL(this.files[0]); //獲取圖片的路徑,該路徑不是圖片在本地的路徑
if (objUrl) {
$("#pic").attr("src", objUrl); //將圖片路徑存入src中,顯示出圖片
upimg();
}
});
});
});
//建立一?可存取到?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;
}
//上傳頭像到服務器
function upimg() {
var pic = $('#upload')[0].files[0];
var file = new FormData();
file.append('image', pic);
$.ajax({
url: "",
type: "post",
data: file,
cache: false,
contentType: false,
processData: false,
success: function(data) {
var res = data;
$("#resimg").append("<img src='/" + res + "'>")
}
});
}