js实现图片上传即时显示效果

发布时间:2020-09-02 16:43:20 作者:逝不等琴生
来源:脚本之家 阅读:129

前言

h6实训时实现的一个图片上传即时显示的效果,如下图所示

js实现图片上传即时显示效果

正文

Html代码

<form action="" method="POST" role="form">
 <div class="form-group">
 <label for="touxiang" >头像上传:</label>
 <input type="file" id="headPhoto" name="headPhoto" />
 <div ><img id="imag" src="img/up.png" alt="" ></div>
 </div> 
</form>

js脚本代码

<script>
 /*显示上传的图片*/
  function getObjectURL(file) {
   var url = null ;
   if (window.createObjectURL!=undefined) {
   url = window.createObjectURL(file) ;
   } else if (window.URL!=undefined) {
   url = window.URL.createObjectURL(file) ;
   } else if (window.webkitURL!=undefined) { 
   url = window.webkitURL.createObjectURL(file) ;
   }
   return url ;
  }
  $('#headPhoto').change(function() {
   var eImg=$('#imag');
   eImg.attr('src', getObjectURL($(this)[0].files[0]));
   $(this).after(eImg);
  });

</script>

window.URL.createObjectURL方法
创建一个新的对象URL,该对象URL可以代表某一个指定的File对象或Blob对象.

语法:

objectURL = window.URL.createObjectURL(blob);
blob参数是一个File对象或者Blob对象.
objectURL是生成的对象URL.通过这个URL,可以获取到所指定文件的完整内容.

完整代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <meta http-equiv="X-UA-Compatible" content="ie=edge">
 <title>图片上传</title>
 <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
 <link href=https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css rel="stylesheet">
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
 
 <form action="" method="POST" role="form">
 <div class="form-group">
 <label for="touxiang" >头像上传:</label>
 <input type="file" id="headPhoto" name="headPhoto" />
 <div ><img id="imag" src="img/up.png" alt="" ></div>
 </div> 
 </form>

</body>
<script>
 /*显示上传的图片*/
  function getObjectURL(file) {
   var url = null ;
   if (window.createObjectURL!=undefined) {
   url = window.createObjectURL(file) ;
   } else if (window.URL!=undefined) { 
   url = window.URL.createObjectURL(file) ;
   } else if (window.webkitURL!=undefined) { 
   url = window.webkitURL.createObjectURL(file) ;
   }
   return url ;
  }
  $('#headPhoto').change(function() {
   var eImg=$('#imag');
   eImg.attr('src', getObjectURL($(this)[0].files[0]));
   $(this).after(eImg);
  });
 </script>
</html>

参考:链接

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

推荐阅读:
  1. js中tab下拉显示效果的实现方法
  2. 如何使用JS+HTML5实现图片上传预览效果

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

js 图片上传 j

上一篇:jquery 可编辑表格

下一篇:JavaScript类的继承方法小结【组合继承分析】

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》