在做图片上传的时候,以前使用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">
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的点击事件
});
});
<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);
}
}
});
});