0

I'm currently working on my first webapp, and my task is to load an image from a database and send it over to the client for display. On the server side, I do

res.setHeader('Content-Type', pic.mimetype);
res.sendFile(pic.path,{ root: __dirname });

The request is completed and in the network tab of the Firefox console, I see the response with a small thumbnail of the image attached and its type(image/jpeg) - thus the image is indeed sent.

The problem is that I don't know how to convert the received data in the response on the client side into a File object that I can read or a path that I can set the src of my img tag to. Can someone tell me how to do this? I can't seem to find what I need anywhere.

Here's my code on the client:

var formData = new FormData();
  formData.append("myfile", file);
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
  if (this.readyState === XMLHttpRequest.DONE && this.status == 200){
        // I need some code here that will convert the response data to a File
        // object or something that can eventually be displayed inside an HTML
        //element. 

        document.dispatchEvent(new CustomEvent("displayImage", {'detail': xhr.responseText}));
      }
  };
  xhr.open("PATCH","/picture",true);
  xhr.send(formData);
Meer
  • 2,765
  • 2
  • 19
  • 28
ribarcheto94
  • 436
  • 11
  • 25
  • This might help you http://stackoverflow.com/a/20048852/3951400 In any case I'd look into this track, which is, to represent the image as a base64 encoded string. – E. Sundin Feb 11 '17 at 05:00

1 Answers1

0

Solved! Apparently whenever you set the src of an image to some URL a GET request is executed. So, in order to retrieve the image you want, just make sure you have a GET route with the same URL as the one in your src on your server side. That way the image will be retrieved and displayed automatically. For example if you are images are in /images set both the src and the GET route urls to "/images" and then in your route method, retrieve the file and send it as the response. Don't forget to set the header content as the mime-type for the image when sending the response back to the client.

ribarcheto94
  • 436
  • 11
  • 25