HTML5 FileReader base64图片预览

在做图片上传的时候,以前使用input file然后提交表单,现在可以使用和HTML5的API FileReader来读取图片文件成base64直接赋值给img的src便可以直接显示图片,另为可以将base64的图片字符串直接ajax发送到后台保存;


摘要:

$('xxxxx').on('click',function(){});


$('xxxx').trigger('click');


var file = $('xxxx').prop('files');


file[0]


FileReader


readAsDataURL(file[0])


event.target.result



一、创建HTML图片上传控件(这里隐藏默认input file 美化 美化需要js模拟click 和change事件)

<img src="http://placehold.it/140x140" class="headImg-show">
<input type="file" style="display:none" id="headUrl" name="headUrl">


二、js模拟事件

1、当点击美化的Input file触发真实的input file控件 用到jquery方法 on() 和 trigger()

$(function(){
	//美化input file控件
	$('.headImg-show').on('<strong><span style="color:#ff0000;">click</span></strong>',function(){
		$('#headUrl').<strong><span style="color:#ff0000;">trigger</span></strong>('<strong><span style="color:#ff0000;">click</span></strong>');//触发input file的点击事件
	});
});


2、监控真实input file的change事件 当有图片选择 调用FileReader进行base64转换 

<pre name="code" class="javascript">//<strong><span style="color:#ff0000;">$(input file控件).prop('files') </span></strong>可以在change的时候获取file对象

 

$(function(){
	//给input file控件绑定事件
	$('#headUrl').on('<strong><span style="color:#ff0000;">change</span></strong>',function(){
		//获取input file的图片文件
		var file = $('#headUrl')<span style="color:#ff0000;"><strong>.prop('files')</strong></span>; 
		//图片文件类型判断
		if(!/image\/\w+/.test(<strong><span style="color:#000099;">file[0]</span></strong>.type)){ 
			alert("仅支持图片文件"); 
			return false; 
		} 
		//base64
		if(0 == file.length){
			alert('选择一张图片');
			return false;
		}else{
			if (typeof FileReader == "undefined") {
			    alert('您的浏览器不支持啊');
			}
			var reader = new FileReader(); //实例化一个FileReader
			reader.<strong><span style="color:#ff0000;">readAsDataURL</span></strong>(<span style="color:#000099;"><strong>file[0]</strong></span>); //读取base64
			// reader.readAsText(file[0],"UTF-8"); //读取文本文件
			reader.onload = function(event){
				var fileStr = <span style="color:#ff0000;"><strong>event.target.result</strong></span>;
				$('.headImg-show').attr('src',fileStr);
			}
		}
	});
});







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值