HTML5浏览器端图片预览&生成Base64
原文地址:http://zhangyiheng.com/blog/articles/img_preview.html
本文主要介绍如何通过拖拽方式在浏览器端实现图片预览,并生成图片的Base64编码。 工具链接:图片转Base64。
首先介绍一下FileReader, FileReader对象允许浏览器使用File或Blob对象异步读取存储在用户计算机上的文件(或数据缓冲区)的内容。
有了FileReader就不需要先把文件发送到服务器端,然后再返回到浏览器端显示这种模式了,可以直接在浏览器端读取文件并显示。
DND获取文件
通过对DragAndDrop事件的监听获取文件。
z.event.on(listDiv, "dragenter", this.preventAndStop, this);
z.event.on(listDiv, "dragover", this.preventAndStop, this);
z.event.on(listDiv, "drop", this.handleDrop, this);
加dragenter和dragover监听主要是防止默认拖拽行为的发生,可以防止浏览器将当前页面变成浏览拖拽进来的图片内容。
在drop事件监听中,可以通过dataTransfer获取拖拽到当前区域的文件列表。
var dt = evt.dataTransfer;
var files = dt.files;
this.readFiles(files);
FileReader读取文件
通过FileReader对象读取文件, 因为FileReader读取文件是异步操作,所以通过onload事件回调来获取读取到的文件内容。
var img = z.dom.create("img", "item");
var reader = new FileReader();
reader.onload = function (e) {
img.src = e.target.result;
}
reader.readAsDataURL(file);
这样用户计算机中的图片文件,就可以在浏览器中预览看到了。
在此通过文件的type做了一些过滤,只读取图片类型的文件,具体实现请参考完成代码。
生成Base64
FileReader读取到的内容,其实就是文件的Base64编码内容,可以直接通过img.src来访问。
完整代码
/**
* Created by taozh on 2017/11/22.
*/
var ToBase64 = {
init: function () {
this.initController();
},
initController: function () {
var listDiv = z.dom.get("#listDiv");
z.event.on(listDiv, "dragenter", this.preventAndStop, this);
z.event.on(listDiv, "dragover", this.preventAndStop, this);
z.event.on(listDiv, "drop", this.handleDrop, this);
z.event.on(listDiv, "click", this.handleClick, this);
},
preventAndStop: function (evt) {
evt.stopPropagation();
evt.preventDefault();
}, handleDrop: function (evt) {
this.preventAndStop(evt);
var dt = evt.dataTransfer;
var files = dt.files;
this.readFiles(files);
},
readFiles: function (files) {
var len = files.length;
for (var i = 0; i < len; i++) {
var file = files[i];
var imageType = /image.*/; if (!file.type.match(imageType)) {
continue;
}
var img = this.addImage(file); if (i === 0) {
this.setCurrent(img);
}
}
},
addImage: function (file) {
var that = this;
var img = z.dom.create("img", "item");
img.file = file;
z.dom.attr(img,"title",file.name);
z.dom.css(img, "display", "none");
var span = z.dom.create("span");
z.dom.get("#listDiv").appendChild(img); var reader = new FileReader();
reader.onerror = function (stuff) {
console.log("error", stuff);
console.log(stuff.getMessage());
};
reader.onload = function (e) {
img.src = e.target.result; z.util.callLater(function () {
var naturalHeight = img.naturalHeight;
var naturalWidth = img.naturalWidth;
if (naturalHeight > 0 && naturalWidth > 0) {
var m = Math.max(naturalWidth, naturalHeight) / 110;
z.dom.css(img, {
width: naturalWidth / m + "px",
height: naturalHeight / m + "px"
})
}
z.dom.css(img, "display", "inline");
if (that.__currentImg === img) {
z.dom.val("#dataPre", img.src);
img.scrollIntoView();
}
}, 200);
};
reader.readAsDataURL(file);
return img;
},
setCurrent: function (img) {
if (this.__currentImg === img) {
return;
}
if (this.__currentImg) {
z.dom.removeClass(this.__currentImg, "active");
z.dom.val("#dataPre", "");
}
this.__currentImg = img;
if (img) {
z.dom.cls(img, "active");
z.dom.val("#dataPre", img.src);
} },
handleClick: function (evt) {
var target = z.event.getTarget(evt);
if (z.dom.hasClass(target, "item")) {
this.setCurrent(target);
}
} };
z.ready(function () {
ToBase64.init();
});
工具链接:图片转Base64
工具效果图:

HTML5浏览器端图片预览&生成Base64的更多相关文章
- js实现移动端图片预览:手势缩放, 手势拖动,双击放大...
.katex { display: block; text-align: center; white-space: nowrap; } .katex-display > .katex > ...
- 适用于各浏览器支持图片预览,无刷新异步上传js插件
文件上传无疑是web应用中一个非常常用的功能,不管是PHP.jsp还是aspx.mvc等都会需要文件上传,但是众所周知当使用自带的文件上传功能时总会出现页面刷新的情况.当然现在有了html5这个好东西 ...
- 记一次IE浏览器做图片预览的坑
随便写写吧,被坑死了 IE 10 及 IE10以上,可以使用FileReader的方式,来做图片预览,加载本地图片显示 IE 9 8 7 没有FileReader这个对象,所以只能使用微软自己的东西来 ...
- jQuery PC端图片预览,鼠标移上去查看大图
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- Vue PC端图片预览插件
*手上的项目刚刚搞完了,记录一下项目中遇到的问题,留做笔记: 需求: 在项目中,需要展示用户上传的一些图片,我从后台接口拿到图片url后放在页面上展示,因为被图片我设置了宽度限制(150px),所以图 ...
- 关于图片预览使用base64在chrome上的性能问题解决方法
在开发后台上传图片的功能时候使用base64预览图片,结果在传入大量图片后导致chrome崩溃,代码如下 var img = new Image(); var render = new FileRea ...
- jquery+html5+canvas实现图片 预览 压缩 上传
javascirpt (function($){ $.fn.extend({ aiiUpload:function(obj) { if(typeof obj !="object") ...
- jq移动端图片预览 (fly-zomm-img.js)
效果图: ===>==> 里面还与很多属性设置: index 关闭按钮等等 代码: //html-----------------------<div class="he ...
- 兼容ie[6-9]、火狐、Chrome、opera、maxthon3、360浏览器的js本地图片预览
html代码: <div id="divPreview"> <img id="imgHeadPhoto" src="Images/H ...
随机推荐
- 【Spring】浅谈spring推荐构造器注入
一.前言 Spring框架对Java开发的重要性不言而喻,其核心特性就是IOC(Inversion of Control, 控制反转)和AOP,平时使用最多的就是其中的IOC,我们通过将组件交由S ...
- Gradle sync failed 异常
今天开发过程中出现如下异常 Gradle sync failed: Connection timed out: connect. If you are behind an HTTP proxy, pl ...
- redis基本教程
http://www.runoob.com/redis/redis-tutorial.html
- LINUX 笔记-Shell 脚本控制语句
1.if 语句 if condition1;then command1 elif condition2;then command2 else command3 fi 2.case 语句 case va ...
- Vue和React对比
Vue和React对比 Vue也已经升级到2.0版本了,到现在为止(2016/11/19)比较流行的MVVM框架有AngularJS(也有人认为其为MVC).ReactJS和VueJS,这三个框架中, ...
- JavaScript的function参数的解释
在js里面写function时其参数在内部表示为一个数组.也就是说:我们定义一个function,里面的参数和将来调用这个function时传入的实参是毫无关系的,如果我们要定义一个function ...
- 关于VRTK的使用(一)—— VR开发环境搭建
首先在Hierarchy窗口中添加GameEmpty,并重命名为VRTK.然后给VRTK添加一个子容器命名为SteamVR.从Asset Store导入SteamVR Plugin: 然后分别选中预制 ...
- LeetCode 566. Reshape the Matrix (重塑矩阵)
In MATLAB, there is a very useful function called 'reshape', which can reshape a matrix into a new o ...
- 仿微信抢红包(js 转)
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...
- 关于IntelliJ IDEA删除项目
刚开始使用IDEA . 自己创建项目玩,结果发现IDEA无法删除,我也是醉了,Eclipse直接右键 -> delete -> 勾选删除源文件 就删除了,IDEA死活没有找到删除选项... ...