mercredi 26 septembre 2018

javascript: I want to show image from raw data

I'm serious. this is making me going crazy.

I want to display images from raw data from server(nodejs)
node js code is like that

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

and then sends raw data of image array.
such as [ {"type":"Buffer","data":[137,80,78,71,13,10,26,10,0,0,0,13,...]},
{"type":"Buffer","data: ....,}]

I think it's raw data. so I tried encoding it to base64
and then, creating image object.
this is javascript code.

    function alertContents(){
        if(xhr.readyState===XMLHttpRequest.DONE){
            if(xhr.status===200){
                let object=JSON.parse(xhr.response);
                let base=btoa(object[0].data.toString());
                console.log(base)

                let image=new Image();
                image.src=`data:image/png; base64,${base}`
                document.body.appendChild(image);
            }else{
                alert(` :'( `);
            }
        }
    }

and this is html.

<body>
<button id="ajaxButton" type="button" onclick="makeRequest()"> HI </button>

</body>

but It doesn't work properly. no error but no loading image.
could you help me out? :'(
seriously, I'm struggling to solve this for couple of hours.
but it's really difficult for me




Aucun commentaire:

Enregistrer un commentaire