Skip to content

Instantly share code, notes, and snippets.

@shenduxian1
Created October 20, 2014 11:33
Show Gist options
  • Save shenduxian1/4bf016f9c0fb50598feb to your computer and use it in GitHub Desktop.
Save shenduxian1/4bf016f9c0fb50598feb to your computer and use it in GitHub Desktop.
移动端获取本地图片并预览
/* 文件上传预览图 */
function FileLoad(settings) {
this.input = settings.input; //input["file"]
this.imgView = settings.imgView;//预览图片容器
this.delBtn = settings.delBtn; //删除按钮
this.init();
}
FileLoad.prototype = {
init: function () {
var _this = this;
if (typeof(FileReader) === 'undefined') {
} else {
this.input.on("change", function () {
_this.readFile.call(_this);
});
}
_this.delBtn.on("click", function (e) {
_this.imgView.html("");
_this.input.val("");
$(this).hide();
})
},
readFile: function () {
var _this = this;
var file = this.input[0].files[0];
var fileType = file.type;//有些安卓浏览器识别不到这个属性
if (fileType && !/image\/\w+/.test(file.type)) {
alert("请上传图片文件")
return false;
}
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function (e) {
if (!fileType) { //当安卓低版本识别不到这个属性时,需要强制的把转化后的base64指定类型
var imgSrc = e.target.result.replace(/data:/, "data:image/png;");
} else {
var imgSrc = e.target.result;
}
_this.imgView.html('<img src="' + imgSrc + '"/>');
_this.delBtn.show();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment