FileReader gets the BASE64 code of the picture and previews it

Keywords: JQuery IE Javascript

FileReader gets base64 code of picture and previews it

FileReader, to be honest, I'm not familiar with it. It's just a record of usage here.

Method name parameter describe
abort none Interrupt read
readAsBinaryString file(blob) Read file as binary
readAsDataURL file(blob) Read file as DataURL
readAsText file, (blob) Read file as text

FileReader contains a complete set of event model to capture the state of reading files

Event describe
onabort Triggered on interrupt
onerror Triggered on error
onload Triggered when the file read completes successfully
onloadend Read completion trigger, regardless of success or failure
onloadstart Triggered at start of read
onprogress In reading

Once the file is read, the result property of the instance will be filled in regardless of success or failure. If the reading fails, the value of result is null. Otherwise, it is the result of reading. Most programs will grab this value when they successfully read the file.

demo

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title></title>
    <link rel="stylesheet" href="">
</head>
<body>
<input type="file" class="file" name="imgfile" id="imgfile" placeholder="Please select a file">
<img src="" id="showImg" >

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<script>
var input = document.getElementById("imgfile");
//Check whether the browser supports FileReader
 if (typeof (FileReader) === 'undefined') {
     result.innerHTML = "Sorry, your browser doesn't support FileReader,Please use modern browser to operate!";
     input.setAttribute('disabled', 'disabled');
 } else {
 //Turn on monitoring
     input.addEventListener('change', readFile, false);
 }
function readFile() {
    var file = this.files[0];

     //Limit the type of uploaded file and judge whether it is a picture type
     if (!/image\/\w+/.test(file.type)) {
         alert("Only pictures can be selected");
         return false;
    }
     var reader = new FileReader();
     reader.readAsDataURL(file);
     reader.onload = function (e) {
       base64Code=this.result;
        //Assign the resulting base64 to the img tag display
       $("#showImg").attr("src",base64Code);
     }
  }
</script>


</body>
</html>

Posted by RazorICE on Tue, 31 Mar 2020 09:23:34 -0700