使用js实现html5界面的图片预览

由于web开发需要,需要在用户在web界面从本地选择文件(图像),选择完成之后,在html5界面中显示(预览),下面介绍如何用JavaScript来实现

1、前端html代码

使用bootstrap前端框架

<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.4.1/dist/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    <title>图片预览测试</title>
  </head>
  <body>

    <div class="container mt-3">
      <div class="container">
        <form>
          <div class="form-group">
            <label for="exampleFormControlFile1" style="font-size: 30px;">请选择图片</label>
            <div class="row">
                <div class="col-6">
                    <!-- 用户完成选择文件,就会触发js中fileSelected()的函数代码,从而实现图像预览 -->
                  <input type="file"  id="exampleFormControlFile" name="file" style="width: 200px;" onchange="fileSelected()">
                  <button type="button" class="btn btn-primary" id="button-submit">确认</button>
                </div>
                <div class="col-6">          
                </div>
            </div>
          </div>
        </form>
      </div>
      <div class="container">
        <div class="row">
            <!-- 需要预览的图片显示区 -->
            <div class="col-8"><img id="preview" width="600" ></div>
            <div class="col-4">
            </div>
        </div>
      </div>
    </div>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.4.1/dist/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
    </body>
</html>

2、JS代码

这个js代码放在body中

<script>
      function fileSelected(){
          // 这个地方通过id号获取输入文件对象
        var oFile = document.getElementById('exampleFormControlFile').files[0];
          // 通过id号获取预览的图像显示区
        var oImage = document.getElementById('preview');
        // prepare HTML5 FileReader
        var oReader = new FileReader();
        oReader.onload = function(e){
            oImage.src = e.target.result;
            oImage.onload = function (){
              // do no thing
            };
          };
        // read selected file as DataURL
        oReader.readAsDataURL(oFile);
      }
</script>

3、测试

效果


0

Leave a Reply

Your email address will not be published.