Jquery上传图片并回显

今天帮后端同事写一段js,需求是使用jQuery上传图片并回显,百度了一下,找了一篇比较符合的文章,记录一下,参考地址:http://www.jq22.com/webqd1622。直接上代码:


<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://libs.baidu.com/jquery/1.11.3/jquery.min.js">script>
  <style>
    html * {
      
      margin: 0;
      padding: 0;
    }
    .picture-container {
      
      position: relative;
      margin: 15px;
      display: flex;
      flex-direction: column;
      width: 180px;
    }

    .picture-echo {
      
      position: absolute;
      top: 0;
      left: 0;
      z-index: 1;
    }

    .echo-img {
      
      width: 180px;
      height: 120px;
      margin: 0;
    }

    .picture-wrap {
      
      width: 180px;
      height: 120px;
      position: relative;
      box-sizing: border-box;
      border: 1px solid #cfdadd;
    }

    /* .wrap {
      background: url(../../res/images/kyc_idcard_a.png);
    } */

    .input-upload-file {
      
      position: absolute;
      width: 180px;
      height: 120px;
      top: 0;
      left: 0;
      cursor: pointer;
      z-index: 3;
      opacity: 0;
    }

    .upload-div {
      
      width: 180px;
      height: 120px;
      position: absolute;
      top: 0;
      opacity: 0;
      z-index: 3;
      cursor: pointer;
    }

    .picture-title {
      
      padding-top: 10px;
      text-align: center;
    }
  style>
head>

<body>
  <div class="picture-container">
    <div class="picture-echo" id="echoImgWrap" style="display: none;">
      <img id="echoImg" src="" class="echo-img" />
    div>
    <div class="picture-wrap wrap">
      <input id="idcardFront" name="idcardFront" class="input-upload-file" type="file"
        accept="image/jpeg, image/jpg, image/png" onchange="tellFun(event, '#echoImg');" />
      <div class="upload-div" id="uploadDiv" onclick="uploadClick('#idcardFront')">div>
    div>
    <div class="picture-title">
      <span>证件正面照片span><br />
      <span>点击上传span>
    div>
  div>
  <script type="text/javascript">
    function uploadClick(id) {
      
      $(id).click();
    }
    function uploadImg(id, file) {
      
      var reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = function (res) {
      
        $(id).attr("src", this.result);
        $(id + 'Wrap').css("display", 'block');
      };
    }
    // 上传文件
    function tellFun(e, picId) {
      
      var imgBox = e.target;
      var file = e.target.files[0];
      if (file.size > 8 * 1024 * 1024) {
      
        // 文件过大
        e.target.value = '';
      } else {
      
        uploadImg(picId, file)
      }
    }
  script>
body>

html>

简单的图片上传,预览

基于jquery和H5的new FileReader

通过readAsResult获取图片的路径

适用于小图片,如头像、身份证照片上传等应用。

你可能感兴趣的:(jQuery,html5,web)