html代码:
<img id="pic" src="img/pic.png"/>
</span><input id="file" type="file" accept="image/*" capture="camera"/>
注意:IOS和Android有兼容性问题,IOS只能拍照,不能从相册选择
解决:
1 $(function () {
2 //解决上传图片时capture="camera"在安卓与IOS的兼容性问题(在IOS只能拍照,不能选相册)
3 var ua = navigator.userAgent.toLowerCase();//获取浏览器的userAgent,并转化为小写——注:userAgent是用户可以修改的
4 var isIos = (ua.indexOf('iphone') != -1) || (ua.indexOf('ipad') != -1);//判断是否是苹果手机,是则是true
5 if (isIos) {
6 $("input:file").removeAttr("capture");
7 };
8 })
js代码:
//选择图片后自动填充
//获取对象input file 的图片地址,放进img
$("#file").change(function () {//input的id
var objUrl = getObjectURL(this.files[0]);//调用函数调取图片地址
obUrl = objUrl;
console.log("objUrl = " + objUrl);
if (objUrl) {
$("#pic").attr("src", objUrl).show();//选择img的ID,给src赋值
}
});
//获取input file的文件地址
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;
}