I have an image file in the server side, and would like to send this image to the client side to display it in the web. It seems like URL.createObjectURL can only be used in a DOM, it sounds impossible to convert the image file to URL in expressJS, or is there any other way to return the image as URL from server side?
I am now trying to send the image buffer and try to use URL.createObjectURL on the client side. It seems like res containing a bunch of weird character string, and I tried to create a Blob, but the image does not render on the web at all.
fetch(`http://localhost:9000/foo`)
.then((res) => res.text())
.then((res) => {
var test = new Blob([res], { type: "image/jpeg" });
props.setImageSrc((prev) => [
...prev,
URL.createObjectURL(test),
]);
});
router.get("/", function (req, res, next) {
var buffer = fs.readFileSync("/Users/foo/bar/image1.jpeg");
var bufferBase64 = new Buffer.from(buffer);
res.send(bufferBase64);
});
Below are part of the res I got on the client side
%&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz�������������������
Use this function to convert the base64 buffer string to blob
const b64toblob = (string, fileType) => {
const byteCharacters = atob(string);
const byteNumbers = new Array(byteCharacters.length);
for (let i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
return new Blob([byteArray], { type: `image/${fileType}` });
};
Receive base64 buffer string from server
fetch(`http://localhost:9000/foo`)
.then((res) => res.text())
.then((res) => {
const blob = b64toblob(buffer, "jpeg");
props.setImageSrc((prev) => [
...prev,
URL.createObjectURL(blob),
]);
});
In server, read the file and convert to base64 buffer
router.get("/", function (req, res, next) {
var buffer = fs.readFileSync("/Users/foo/bar/image1.jpeg");
var bufferBase64 = new Buffer.from(buffer);
res.send(bufferBase64.toString("base64"));
});