使用说明:新建文件,直接复制粘贴,保存文件为html 格式,在浏览器运行即可;

第一种:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title> New Document </title>
</head> <script src="http://i.gtimg.cn/qzone/biz/gdt/lib/jquery/jquery-2.1.4.js?max_age=31536000"></script> <script> $(function(){
$('#upLoad').on('change',function(){
var filePath = $(this).val(), //获取到input的value,里面是文件的路径
fileFormat = filePath.substring(filePath.lastIndexOf(".")).toLowerCase(),
imgBase64 = '', //存储图片的imgBase64
fileObj = document.getElementById('upLoad').files[0]; //上传文件的对象,要这样写才行,用jquery写法获取不到对象 // 检查是否是图片
if( !fileFormat.match(/.png|.jpg|.jpeg/) ) {
alert('上传错误,文件格式必须为:png/jpg/jpeg');
return;
} // 调用函数,对图片进行压缩
compress(fileObj,function(imgBase64){
imgBase64 = imgBase64; //存储转换的base64编码
$('#viewImg').attr('src',imgBase64); //显示预览图片
});
}); // 不对图片进行压缩,直接转成base64
function directTurnIntoBase64(fileObj,callback){
var r = new FileReader();
// 转成base64
r.onload = function(){
//变成字符串
imgBase64 = r.result;
console.log(imgBase64);
callback(imgBase64);
}
r.readAsDataURL(fileObj); //转成Base64格式
} // 对图片进行压缩
function compress(fileObj, callback) {
if ( typeof (FileReader) === 'undefined') {
console.log("当前浏览器内核不支持base64图标压缩");
//调用上传方式不压缩
directTurnIntoBase64(fileObj,callback);
} else {
try {
var reader = new FileReader();
reader.onload = function (e) {
var image = $('<img/>');
image.load(function(){
square = 700, //定义画布的大小,也就是图片压缩之后的像素
canvas = document.createElement('canvas'),
context = canvas.getContext('2d'),
imageWidth = 0, //压缩图片的大小
imageHeight = 0,
offsetX = 0,
offsetY = 0,
data = ''; canvas.width = square;
canvas.height = square;
context.clearRect(0, 0, square, square); if (this.width > this.height) {
imageWidth = Math.round(square * this.width / this.height);
imageHeight = square;
offsetX = - Math.round((imageWidth - square) / 2);
} else {
imageHeight = Math.round(square * this.height / this.width);
imageWidth = square;
offsetY = - Math.round((imageHeight - square) / 2);
}
context.drawImage(this, offsetX, offsetY, imageWidth, imageHeight);
var data = canvas.toDataURL('image/jpeg');
//压缩完成执行回调
callback(data);
});
image.attr('src', e.target.result);
};
reader.readAsDataURL(fileObj);
}catch(e){
console.log("压缩失败!");
//调用直接上传方式 不压缩
directTurnIntoBase64(fileObj,callback);
}
}
}
}); </script> <body>
<input type="file" id="upLoad" name="image" >
<!-- 显示上传之后的图片 -->
<div id='previewImg'>
<img src="" id='viewImg'/>
</div>
</body>
</html>

第二种:

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<input type="file"><br>
<img src="" height="200" alt="Image preview area..." title="preview-img">
<script>
var fileInput = document.querySelector('input[type=file]'),
previewImg = document.querySelector('img');
fileInput.addEventListener('change', function () {
var file = this.files[0];
var reader = new FileReader();
// 监听reader对象的的onload事件,当图片加载完成时,把base64编码賦值给预览图片
reader.addEventListener("load", function () {
previewImg.src = reader.result;
}, false);
// 调用reader.readAsDataURL()方法,把图片转成base64
reader.readAsDataURL(file);
}, false);
</script>
</body>
</html>

  

HTML添加上传图片并进行预览的更多相关文章

  1. OSS上传图片无法在线预览的解决方案

    OSS上传图片无法在线预览的解决方案 最近在做的项目涉及到商品详情,由于前端用的flutter框架并且该详情为富文本,dart语言关于富文本的组件不是非常友好,当富文本中的图片无法在浏览器中直接预览的 ...

  2. HTML5 CSS3 经典案例:无插件拖拽上传图片 (支持预览与批量) (二)

    转载请标明出处:http://blog.csdn.net/lmj623565791/article/details/31513065 上一篇已经实现了这个项目的整体的HTML和CSS: HTML5 C ...

  3. javascript和HTML5上传图片之前实现预览效果

    一:FileList对象与file对象 FileList对象表示用户选择的文件列表,在HTML4中,file控件内只允许放置一个文件,但是到了HTML5中,通过添加multiple属性,file控件内 ...

  4. 基于jquery实现的上传图片及图片预览效果代码

    <!DOCTYPE html> <html> <head> <title>HTML5上传图片预览</title> <meta http ...

  5. 【android学习3】解决Android界面布局添加EditView之后无法预览问题

    在设计登陆界面时,拖入一个EditView之后发现界面无法预览 问题分析: 进入xml源文件里发现一个警告,提示添加inputType或者hint元素,添加后界面仍然无法预览... 仔细查看了当前使用 ...

  6. 利用FileReader实现上传图片前本地预览

    引子 平时做图片上传预览时如果没有特殊的要求就直接先把图片传到后台去,成功之后拿到URL再渲染到页面上,这样做在图片比较小的时候没什么问题,大一点的话就会比较慢才能看到预览了,而且还产生了垃圾文件,所 ...

  7. JS 上传图片时实现预览

    网页中一张图片可以这样显示: <img src="http://www.letuknowit.com/images/wg.png"/>也可以这样显示:<img s ...

  8. (干货)微信小程序之上传图片和图片预览

    这几天一直负责做微信小程序这一块,也可以说是边做边学习吧,把自己做的微信小程序的一些功能分享出来,与大家探讨一下,相互学习相互进步. 先看下效果图 只写了一下效果样式的话希望大家不要太在意,下面马路杀 ...

  9. 原生js上传图片时的预览

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http ...

随机推荐

  1. Ubuntu下配置LAMP + PhpStorm

    本文仅作为一个记录,以下配置在Ubuntu 14.10 64-bit上验证通过. 安装Apache 2:sudo apt-get install apache2 安装成功能够后,通过浏览器访问loca ...

  2. 03019_过滤器Filter

    1.Filter的简介 (1)Filter是对客户端访问资源的过滤,符合条件放行,不符合条件不放行,并且可以对目标资源访问前后进行逻辑处理: (2)快速入门步骤 ①编写一个过滤器的类实现Filter接 ...

  3. 从事IT业一个8年老兵转行前的自我总结2——从《易经》说开来

    近些年一直在读<易经>,收获颇多.以前看不贯的人或物现在可以淡然看定,以前看不开的一些事现在也安然放下,以前看不透的某些事现在也都可看透八九不离十. 古人云:不读<易>不可为将 ...

  4. USACO Section1.3 Ski Course Design 解题报告

    skidesign解题报告 —— icedream61 博客园(转载请注明出处)------------------------------------------------------------ ...

  5. 【Divided Two】cpp

    题目: Divide two integers without using multiplication, division and mod operator. If it is overflow, ...

  6. leetcode 【 Remove Duplicates from Sorted List II 】 python 实现

    题目: Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct  ...

  7. Python导出sql语句结果到Excel

    本文档是因为每周需要统计线上数据库中客户新增资源,手动执行实在是麻烦,就写了个脚本导出到Excel,顺便发一封邮件. (当然这不是线上的真实脚本,不过根据个人需求稍微修改下,还是可以直接用的.拿去不谢 ...

  8. Python全栈工程师(exercises)

    # # 练习: # # 1. 用map函数求: # # 1**3 + 2**3 + 3 ** 3 + .... 9**3 的和 def add_(x): return x ** 3 print(sum ...

  9. (转)KlayGE游戏引擎 :高效的GBUFFER管理方式

    转载请注明出处为KlayGE游戏引擎,本文的永久链接为http://www.klayge.org/?p=3304 个顶点.这样的数据对GPU来说是很头疼的.所以引擎往往需要在Buffer上做一些工作来 ...

  10. JavaScript里面之dom操作

    1.dom之选择元素 <!DOCTYPE html> <html lang="en"> <head> <meta charset=&quo ...