原文地址: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. Mybatis,Spring,SpringMVC框架面试题

    Mybatis测试 1,   Mybatis的核心是(  sqlsessionfactory    ) 2,   使用Mybatis持久化框架进行数据查询需要返回的一个实体类的集合, 在<sel ...

  2. mybatis 和hibernate的区别

    mybaits 是不完全的orm(对象关系映射(Object Relational Mapping)框架,需要自己书写sql语句 mybatis学习难度必hibernate低适合关系型模型要求不高的软 ...

  3. CSS盒子模型之详解

    前言:        盒子模型是css中最核心的基础知识,理解了这个重要的概念才能更好的排版,进行页面布局.一.css盒子模型概念    CSS盒子模型 又称框模型 (Box Model) ,包含了元 ...

  4. Java中public,protected,default,private的访问权限问题(简明扼要)

    import packa.*;//导入了packa包中所有的类.(不包括包中的子包)一般不会用,用哪个导入哪个. 导包的原则:用到哪个类,就导入哪个类.所有字母都小写. 权限列表:   public ...

  5. 构造函数,This关键字

    构造函数: 即构建创造对象时调用的函数.在new的时候自动执行,给对象进行初始化.创建对象都必须要通过构造函数初始化.(有参和无参) 一个类中如果没有定义过构造函数,那么类中会有一个默认的空参数构造函 ...

  6. TensorFlow问题:The TensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available on your machine and could speed up CPU computations.

    1. 问题描述 The TensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available o ...

  7. win10 uwp 读取文本GBK错误

    本文讲的是解决UWP文本GBK打开乱码错误,如何去读取GBK,包括网页GBK.最后本文给出一个方法追加文本. 我使用NotePad记事本保存文件,格式ASCII,用微软示例打开文件方式读取,出现错误 ...

  8. 走进 Xamarin Test Recorder for Xamarin.Forms

    此篇是承接之前 走进 UITest for Xamarin.Forms 的,所以如果没有看过之前的可以先看下之前的 UITest 比起上一篇纯敲代码只适合程序员的 UITest ,这一篇不管是程序员还 ...

  9. Spring Cloud官方文档中文版-Spring Cloud Config(下)-客户端等

    官方文档地址为:http://cloud.spring.io/spring-cloud-static/Dalston.SR2/#_serving_alternative_formats 文中例子我做了 ...

  10. #1094 : Lost in the City by C solution

    时间限制:10000ms 单点时限:1000ms 内存限制:256MB 描述 Little Hi gets lost in the city. He does not know where he is ...