mardi 18 septembre 2018

get image from server with XmlHttpRequest

I'm developing website with html, css, javascript and node.
And I want to display some images from server.

This is Server Code

app.use('/all_pic',(req,res)=> {
  let arr=[];

    fs.readdir(testFolder, (err, files) => {
      files.forEach(file=>{
        let file_name="./uploads/"+file;
        let data=fs.readFileSync(file_name);
        arr.push(data)
      })
    })

    setTimeout(()=>{
      console.log(arr);
      res.send(arr);
    },1000);
})

this is to read all png images in a certain directory and send array to client interface.

And this is html Code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ddd</title>
</head>
<body>
    <div id="demo">
        <h2>blah blah</h2>
        <button type="button" onclick="loadDoc()"> change content</button>
    </div>

    <script>
        function loadDoc(){
            var xhttp=new XMLHttpRequest();
            xhttp.onreadystatechange = function(){
                if(this.readyState==4 && this.status == 200){
                    document.getElementById("demo").innerHTML=
                        this.response;
                }
            };
            xhttp.open("GET", "http://localhost:3000/all_pic", true);
            xhttp.send();
        }
    </script>

</body>
</html>

and the result is like..

[{"type":"Buffer","data":[137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,2,214,0,0,0,75,8,6,0,0,0,84,119,192,114,0,0,24,31,105,67,67,80,73,67,67,32,80,.....]}, {"type":"Buffer","data":[137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,2,214,0,0,0,75,8,6,0,0,0,84,119,192,114,0,0,24,31,105,67,67,80,73,67,67,32,80,.....]}]

it's binary code. (Actually string)
I don't have no idea how I can get images not binary code.
do I need a stage of encoding?

I would appreciate your helping:)
Many thanks.




Aucun commentaire:

Enregistrer un commentaire