jQuery 如何在jquery中上传之前预览图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18694437/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 22:13:48  来源:igfitidea点击:

How to preview image before uploading in jquery

jquery

提问by Salim Qureshi

I can read the uploaded image by using javascript fileReader but how can i read the uploaded image in jquery so that i can preview the image before uploading ?

我可以使用 javascript fileReader 读取上传的图像,但是如何在 jquery 中读取上传的图像,以便在上传前预览图像?

回答by Suresh Pattu

function readURL(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();
    reader.onload = function(e) {
      $('#previewHolder').attr('src', e.target.result);
    }

    reader.readAsDataURL(input.files[0]);
  }
}

$("#filePhoto").change(function() {
  readURL(this);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="file" name="filePhoto" value="" id="filePhoto" class="required borrowerImageFile" data-errormsg="PhotoUploadErrorMsg">
<img id="previewHolder" alt="Uploaded Image Preview Holder" width="250px" height="250px"/>

回答by vijay pancholi

// using javascript 
<div class="form-group">
     
   <label for="password" class="form-group">upload Image</label>
  
  <input id="image" type="file" name="image"   onchange="document.getElementById('blah').src = window.URL.createObjectURL(this.files[0])" required="required"><img id="blah"  width="50" height="50" />
   </div>

回答by vijay pancholi

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
  <script src="jquery-3.1.1.min.js"></script>
  <script src="//code.jquery.com/jquery-1.9.1.js"></script>
  <script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
  
<style type="text/css">
p1{
    color:orange;
}
p2{
    color:green;
}

 .thumb-image
 {
    float:left;
    width:50px;
    position:relative;
    padding:2px;
}

body{
                
                }
        
            #form label{
                font:bold 11px arial;
                color: #565656;
                padding-left: 1px;
            }
            #form label.mandat{color:red;}
            
           
            #form img{
                margin-bottom: 8px;
            }
            #form input[type="submit"]{
                background-color: #0064aa;
                border: none;
                color: #fff;
                padding: 5px 8px;
                cursor: pointer;
                font:bold 12px arial;
            }
            .error{
                border: 1px solid olive;
            }
            


</style>
  
  <script>
$.validator.addMethod("error9", function(value, element, error) {          
    return error.test(value);
} );




  $(function() {
  
  
    $("#register-form").validate({
    
       
        rules: {
           
               
        pic: {
            required: true,
            error9: /(?=.(gif|png|jpg|jpeg))/

        }
        
        

        },

        messages: {


          
            pic: {
            required: "<p1>Please upload image</p1>",
            error9: "<p2> only accept jpg,gif,png</p2>"
        }

           
        },
        
        submitHandler: function(form) {
            form.submit();
        }
    });

  });
  
  </script>
  <script>
$(document).ready(function() {
        $("#pic").on('change', function() {
          //Get count of selected files
          var countFiles = $(this)[0].files.length;
          var imgPath = $(this)[0].value;
          var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
          var image_holder = $("#image-holder");
          image_holder.empty();
          if (extn == "gif" || extn == "png" || extn == "jpg" || extn == "jpeg") {
            if (typeof(FileReader) != "undefined") {
              //loop for each file selected for uploaded.
              for (var i = 0; i < countFiles; i++) 
              {
                var reader = new FileReader();
                reader.onload = function(e) {
                  $("<img />", {
                    "src": e.target.result,
                    "class": "thumb-image"
                  }).appendTo(image_holder);
                }
                image_holder.show();
                reader.readAsDataURL($(this)[0].files[i]);
              }
            } else {
              echo (image_holder);
            }
          } else {
            //alert ("Pls select only images");
          }
        });
      });
</script>


</head>
<body>

 <div style='margin:0 auto'>

<form name= "" id="register-form" action="loginformjq.php"  method="post">
<div id="form">
<table  border="1" padding="2" cellpadding="2" width="20%" bgcolor="lightblue" align="center" cellspacing="2">

<tr>
<td colspan=2>
<center><font size=4><p style="color: purple"><marquee direction="left" behavior="alternate" style="border:solid olive">Student Registration Form</marquee></p></font></center>
</td>
</tr>
               
                    
<tr><p style="color: yellow"><td>
<p class="error">
     <input type="file" name="pic"  id="pic"></p><span id="image-holder"> </span>
     </p></td></tr>



<tr>
<p style="color: yellow"></p>
<td colspan="1"><input type="submit" value="submit"></td>

</tr>
</table>
</form>
  
</div>
        
        
        </div>
</body>
</html>