节点将文件作为 URL 发送
我在服务器端有一个图像文件,并且想将该图像发送到客户端以在网络中显示它。似乎 URL.createObjectURL
只能在 DOM 中使用,听起来不可能在expressJS中将图像文件转换为 URL,或者是否有其他方法从服务器端将图像作为 URL 返回?
我现在尝试发送图像缓冲区并尝试在客户端使用 URL.createObjectURL
。看起来 res
包含一堆奇怪的字符串,我尝试创建一个 Blob,但图像根本无法在网络上呈现。
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);
});
以下是我在客户端得到的部分资源 %&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz��������������������
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�������������������
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用此函数将base64缓冲区字符串转换为blob
从服务器接收base64缓冲区字符串
在服务器中,读取文件并转换为base64缓冲区
Use this function to convert the base64 buffer string to blob
Receive base64 buffer string from server
In server, read the file and convert to base64 buffer