简体   繁体   中英

How to encode and decode the uploaded file using input type file

I have created multiple file upload option for user. I want to encode and decode the uploaded file... Here i write the program for convert the image to base64 string... How to encode as well as decode the file using base64.

My Code is

<html>
<body>

<input id="inputFileToLoad" type="file" onchange="encodeImageFileAsURL();" multiple />
<div id="imgTest"></div>
<script type='text/javascript'>
  function encodeImageFileAsURL() {

    var filesSelected = document.getElementById("inputFileToLoad").files;
    if (filesSelected.length > 0) {
      var fileToLoad = filesSelected[0];

      var fileReader = new FileReader();

      fileReader.onload = function(fileLoadedEvent) {
        var srcData = fileLoadedEvent.target.result; // <--- data: base64

        var newImage = document.createElement('img');
        newImage.src = srcData;

        document.getElementById("imgTest").innerHTML = newImage.outerHTML;
        alert("Converted Base64 version is " +          document.getElementById("imgTest").innerHTML);
        var reslut =    document.getElementById("imgTest").innerHTML; 
        console.log("Converted Base64 version is " +reslut);

      }
      fileReader.readAsDataURL(fileToLoad);
    }
  }
</script>
</body>
</html>

In console i print the encoded value of file... How to use console output for decode purpose.

尝试window.atob(base64string) ,我认为它是一个blob对象的utf8字符串

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM