码迷,mamicode.com
首页 > Web开发 > 详细

利用html5实现上传图片预览

时间:2015-08-11 19:25:19      阅读:103      评论:0      收藏:0      [点我收藏+]

标签:html5

在HTML5中,通过FileReader可以轻松的实现这个功能。


只要在<input type="file" />文件表单元素中监听 onchange 事件,然后通过FileReader读取图片文件,然后将读取的内容在<img>中显示即可。

 


实现代码

 

<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="utf-8" />
<meta name="author" content="EdieLei" />
<title>HTML5 图片上传预览</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function(){
    $(‘#img‘).change(function(){
        var file = this.files[0];    //选择上传的文件
        var r = new FileReader();
        r.readAsDataURL(file);    //Base64
        $(r).load(function(){
            $(‘div‘).html(‘<img src="‘+ this.result +‘"  />‘);
        });
    });
});
</script>
</head>
<body>
<h3>HTML5 图片上传预览</h3>
<input id="img" type="file" accept="image/*" /><br />
<div></div>
</body>
</html>



参考资料: html5实现上传图片预览   http://www.studyofnet.com/news/856.html

 

本文出自 “学习也休闲” 博客,请务必保留此出处http://studyofnet.blog.51cto.com/8142094/1683530

利用html5实现上传图片预览

标签:html5

原文地址:http://studyofnet.blog.51cto.com/8142094/1683530

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!