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

(编辑:jimmy 日期: 2025/3/20 浏览:2)

前言

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

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="/UploadFiles/2021-04-02/up.png">

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="/UploadFiles/2021-04-02/jquery.js">

参考:链接

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

一句话新闻

高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。