Html reads the pictures in the local folder and displays

One purpose

Select the local folder on Html, automatically read all pictures under the folder and subfolder and display them on the page.

Technical analysis:

Existing problems

  • The path obtained by the file tag in Html is relative.
  • The absolute path is required when the source is specified by Img in Html.
  • resolvent:
    Call the readAsDataURL method in the Web API interface FileReader to read the data (the file path obtained by the function parameter file label), and then load the data into the FileReader (base64 format). After that, you can use image to specify the data in base64 format at the source time and draw pictures.

Two code

<!DOCTYPE html>
    <input type="file" id="selectFiles" onchange="dealSelectFiles()" multiple webkitdirectory>
    <canvas id="myCanvas" width=1440 height=900></canvas>
    <script type="text/javascript">
        var imgPosX = 0;
        var imgWidth = 256;
        function dealSelectFiles(){
            /// get select files.
            var selectFiles = document.getElementById("selectFiles").files;
            for(var file of selectFiles){
                /// read file content.
                var reader = new FileReader();
                reader.onloadend = function(){
                    /// deal data.
                    var img = new Image();
                    /// after loader, result storage the file content result.
                    img.src = this.result;  
                    img.onload = function(){
                        var myCanvas = document.getElementById("myCanvas");
                        var cxt = myCanvas.getContext('2d');
                        cxt.drawImage(img, imgPosX, 0);
                        imgPosX += imgWidth;

Three effect


Tags: Javascript

Posted on Tue, 03 Dec 2019 00:16:32 -0500 by manimoor