Currently, I am developing my first web application and the task at hand involves loading an image from a database and sending it to the client for display. On the server side, I have the following code:
res.setHeader('Content-Type', pic.mimetype);
res.sendFile(pic.path,{ root: __dirname });
The request is successfully completed and in the network tab of the Firefox console
, I can see the response with a small thumbnail of the image attached along with its type (image/jpeg) - indicating that the image has been sent.
However, the issue arises when trying to convert the received data in the response on the client side into a File object that can be read or a path that can be set as the src attribute of an img tag. I have searched extensively but haven't found a solution so far.
Below is the code snippet on the client side:
var formData = new FormData();
formData.append("myfile", file);
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState === XMLHttpRequest.DONE && this.status == 200){
// Code needed here to convert the response data into a File object or something that can be displayed inside an HTML element.
document.dispatchEvent(new CustomEvent("displayImage", {'detail': xhr.responseText}));
}
};
xhr.open("PATCH","/picture",true);
xhr.send(formData);