html:
<img id="pic" src="" >
<input id="upload" name="file" accept="image/*" type="file" style="display: none"/>
input:file事件是上传类型
较常用的属性值如下:
accept:表示可以选择的文件MIME类型,多个MIME类型用英文逗号分开,常用的MIME类型见下表。
若要支持所有图片格式,则写 * 即可。
multiple:是否可以选择多个文件,多个文件时其value值为第一个文件的虚拟路径
input:file的样式是不变的,所以若要改变它的样式,首先将它隐藏。display:none;
jquery:
$(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中,显示出图片}});});});//建立一個可存取到該file的urlfunction getObjectURL(file) {var url = null ;if (window.createObjectURL!=undefined) { // basicurl = window.createObjectURL(file) ;} else if (window.URL!=undefined) { // mozilla(firefox)url = window.URL.createObjectURL(file) ;} else if (window.webkitURL!=undefined) { // webkit or chromeurl = window.webkitURL.createObjectURL(file) ;}return url ;}
浙公网安备 33010602011771号