前台将input[type="file"]中的上传的图片读取成base64数据

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">
    <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js">script>
    <title>Documenttitle>
    <style>
        .addBorder{ 
            border:1px solid #ccc;
        }
        
        #imgDiv{
            width:500px;
            height:500px;
        }
        
        #imgDiv > img{
            width:100%;
        }

    style>
head>
<body>

    <form id="imgForm">
        <input type="file" class="addBorder"  multiple="multiple" id='imgs'>
        <br/>
        <button type="button" onclick="loadImg_test()">获取图片button>
    form>
        
    <div  id="imgDiv">
      
    div>

    <script>
        function loadImg_test(){
            var files = $('#imgs')[0].files;
           
            var readFile = function(file){
                return new Promise(function(resolve,reject){
                    var reader = new FileReader();
                    reader.onload = function (e){    
                        resolve(e.target.result);                    
                    }
                    reader.readAsDataURL(file);             
                })
            }

            var gen = async function(){
                var f,img;
                for(var i = 0,l = files.length;i < l; i++){
                    f = await readFile(files[i]);   
                    img = document.createElement('img');
                    img.src = f;
                    $('#imgDiv').append(img);
                }             
            }
            gen();        
        }
    script>
body>
html>

 

转载于:https://www.cnblogs.com/kerryw/p/9548327.html

你可能感兴趣的:(前台将input[type="file"]中的上传的图片读取成base64数据)