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 ...
随机推荐
- Admob - Google广告接入
前言 现在免费小游戏及应用的主要收入渠道就是通过接入广告.而Google的Admob适用于全球范围内的广告接入,文档方面及后台管理也是较为完善,接入还是比较便捷的. 不过Google目前还在墙外,虽然 ...
- 初识SQL Server2017 图数据库(一)
背景: 图数据库对于表现和遍历复杂的实体之间关系是很有效果的.而这些在传统的关系型数据库中尤其是对于报表而言很难实现.如果把传统关系型数据库比做火车的话,那么到现在大数据时代,图数据库可比做高铁.它已 ...
- 容器中使用iptables报错can't initialize iptables table Permission denied (you must be root)
背景 在docker容器中部署了一微服务,该服务需要docker push镜像到docker registry.因此,docker容器中需要安装docker服务.但在启动容器的时候,却报错: can' ...
- win10 uwp iot
这篇文章主要译: https://msdn.microsoft.com/magazine/mt694090 有很多都是胡说,随便喷,但我不会理. https://blogs.msdn.microsof ...
- HTML之事件处理程序
HTML事件 <body> <input type="button" value="按钮1" id="but1" oncl ...
- Spring装配Bean之XML装配bean
在Spring刚出现的时候,XML是描述配置的主要方式,在Spring的名义下,我们创建了无数行XML代码.在一定程度上,Spring成为了XML的同义词. 现在随着强大的自动化配置和Java代码的配 ...
- ios 返回不会自动刷新页面问题
在实际开发过程中,移动端的兼容性问题有很大的坑,安卓可以了ios不行,ios可以了安卓又失效了这样,其中ios的回退操作就是不会自动刷新页面,很烦! 常见的history.back() history ...
- Fastify 系列教程二 (中间件、钩子函数和装饰器)
Fastify 系列教程: Fastify 系列教程一 (路由和日志) Fastify 系列教程二 (中间件.钩子函数和装饰器) 中间件 Fastify 提供了与 Express 和 Restify ...
- Promise对象解读
首先强调的是"Promise"是对象,也就是说与其他JavaScript对象的用法,没有什么两样:其次,它起到代理作用(proxy),充当异步操作与回调函数之间的中介.它使得异步操 ...
- .1-Vue源码起步
搞事!搞事! 截止2017.5.16,终于把vue的源码全部抄完,总共有9624行,花时大概一个月时间,中间迭代了一个版本(2.2-2.3),部分代码可能不一致,不过没关系! 上一个链接https:/ ...