上传图片时一般都需要预览,我一般用这两种方法来实现。base64编码可以直接上传到后台,后台解析下,得到的文件就会比较小了,省去了压缩图片这一步了。
//获取对象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; } //方法二:获取base64编码 $("#file2").change(function() { var file = this.files[0]; var reader = new FileReader(); reader.readAsDataURL(file); reader.onload = function(e) { alert(this.result); $("#pic").attr("src", this.result).show();//选择img的ID,给src赋值 }; });