原文地址: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的更多相关文章

  1. js实现移动端图片预览:手势缩放, 手势拖动,双击放大...

    .katex { display: block; text-align: center; white-space: nowrap; } .katex-display > .katex > ...

  2. 适用于各浏览器支持图片预览,无刷新异步上传js插件

    文件上传无疑是web应用中一个非常常用的功能,不管是PHP.jsp还是aspx.mvc等都会需要文件上传,但是众所周知当使用自带的文件上传功能时总会出现页面刷新的情况.当然现在有了html5这个好东西 ...

  3. 记一次IE浏览器做图片预览的坑

    随便写写吧,被坑死了 IE 10 及 IE10以上,可以使用FileReader的方式,来做图片预览,加载本地图片显示 IE 9 8 7 没有FileReader这个对象,所以只能使用微软自己的东西来 ...

  4. jQuery PC端图片预览,鼠标移上去查看大图

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  5. Vue PC端图片预览插件

    *手上的项目刚刚搞完了,记录一下项目中遇到的问题,留做笔记: 需求: 在项目中,需要展示用户上传的一些图片,我从后台接口拿到图片url后放在页面上展示,因为被图片我设置了宽度限制(150px),所以图 ...

  6. 关于图片预览使用base64在chrome上的性能问题解决方法

    在开发后台上传图片的功能时候使用base64预览图片,结果在传入大量图片后导致chrome崩溃,代码如下 var img = new Image(); var render = new FileRea ...

  7. jquery+html5+canvas实现图片 预览 压缩 上传

    javascirpt (function($){ $.fn.extend({ aiiUpload:function(obj) { if(typeof obj !="object") ...

  8. jq移动端图片预览 (fly-zomm-img.js)

    效果图: ===>==> 里面还与很多属性设置: index  关闭按钮等等 代码: //html-----------------------<div class="he ...

  9. 兼容ie[6-9]、火狐、Chrome、opera、maxthon3、360浏览器的js本地图片预览

    html代码: <div id="divPreview"> <img id="imgHeadPhoto" src="Images/H ...

随机推荐

  1. Bootstrap表格样式(附源码文件)--Bootstrap

    1.表格默认样式 <h4>表格默认样式</h4><table><!--默认样式--> <tr><th>序号</th> ...

  2. NopCommerce 1. NopCommerce Application_Start启动过程

    这里简单介绍整个启动过程,其他具体的后续讲解 从Application_Start中执行开始,一开始执行EngineContext.Initialize(false); EngineContext 是 ...

  3. win10 uwp 隐藏实时可视化

    新的vs有个功能,实时可视化 但是他会挡我们界面,想要隐藏 点击转到实时可视化,就是点击横线看到,接着就可以看到下面的选项 点击在应用程序中显示运行时,就是不选中 很简单就看到,没有那个 本作品采用知 ...

  4. mysql的读写分离

    1.laravel实现数据库读写分离配置或者多读写分离配置 config\database.php里配置 'connections' => array(      //默认mysql配置,访问t ...

  5. 正六边形网格化(Hexagonal Grids)原理与实现

    在路径规划.游戏设计栅格法应用中,正六边形网格不如矩形网格直接和常见,但是正六边形具有自身的应用特点,更适用于一些特殊场景中,比如旷阔的海洋.区域或者太空.本文主要讲述如何对正六边形进行几何学分析.网 ...

  6. 主要讲下hack的兼容用法,比较浅,哈哈

    hack是主要来处理IE的兼容,不同的IE,不同的兼容方式 /*   属性前缀法(即类内部Hack):       *color:#000; *号对IE6,IE7都生效   +color:#555; ...

  7. 树莓派.GPRS.短信接收器

    起因 曾经用过西门子出的短信猫, 好处是直接有SDK开发包, 不会硬件开发也能直接使用 缺点也是明显的, 就是只支持Windows系统, 另外就是在Windows下工作很不稳定, 隔开几天就会出现收不 ...

  8. LeetCode 617. Merge Two Binary Tree (合并两个二叉树)

    Given two binary trees and imagine that when you put one of them to cover the other, some nodes of t ...

  9. go 代码的调试---打印调用堆栈

    本文介绍如何打印调用堆栈进行go代码的调试. 打印堆栈使用的runtime package中的Stack()函数 func Stack(buf []byte, all bool) int Stack ...

  10. scp命令,用来在本地和远程相互传递文件,非常方便

    scp是secure copy的简写,用于在Linux下进行远程拷贝文件的命令,和它类似的命令有cp,不过cp只是在本机进行拷贝不能跨服务器,而且scp传输是加密的.可能会稍微影响一下速度.当你服务器 ...