【问题标题】:AJAX request png/jpeg image from (NodeJS + Express) server and show it in html来自(NodeJS + Express)服务器的 AJAX 请求 png/jpeg 图像并在 html 中显示
【发布时间】:2019-08-08 01:51:19
【问题描述】:

基本上我需要从我的服务器接收 png 或 jpeg 图像,并将其显示在我网站的 img 标签中。

我的架构如下所示:

客户端-Server1(我的服务器)-Server2(一些公共服务器)

  1. 客户端向 Server1 发送 Ajax 请求。
  2. Server1 向 Server2 发送请求。
  3. Server2 将图像发送回 Server1。
  4. Server1 将图像发送回客户端。

客户端代码:

$("#testButton").click(function() {
  $.ajax({
    method: "get",
    async: false,
    url: "/test"
  }).done(function (response){
    alert(response.imageData);
    $("#resultImage").attr("src", "data:image/png;base64," + response.imageData);
  });
});

Server1 代码:

router.get('/test', function(req, res, next){
  var url = 'https://ion.gemma.feri.um.si/ion/services/geoserver/demo1/wms?service=WMS&version=1.1.0&request=GetMap&layers=demo1%3Amaribor-dof25&bbox=546631.6237364038%2C156484.86830455417%2C550631.7865026393%2C160485.0310707898&width=767&height=768&srs=EPSG%3A3794&format=image%2Fjpeg';
  request(url, function (error, response, body) {
    console.log('error:', error);
    console.log('statusCode:', response && response.statusCode);
    console.log(response.headers['content-type']);
    console.log(body);
    return res.json({ imageData: body});
  });
});

如果我把上面的url直接输入到img src,就显示正确了。 当我直接在浏览器中输入 url 时,图像也能正确显示。

当我从 server1 接收到返回给我的客户端的图像数据时,数据如下所示:

任何想法如何解决这个问题?

【问题讨论】:

  • 你好。是的,您的回答帮助解决了我的问题。谢谢。

标签: javascript html node.js ajax server


【解决方案1】:

由于您在前端构建base64 编码图像,后端必须返回base64 编码图像。

您正在以utf8 格式返回图像,这当然是行不通的。 utf8 是使用request 包时的默认编码。

您可以为此使用 request 包的 encoding 属性。或传递encoding: null 并使用.toString('base64')body 转换为base64 字符串

request({ url, encoding: 'base64' }, function (error, response, body) {
    console.log('error:', error);
    console.log('statusCode:', response && response.statusCode);
    console.log(response.headers['content-type']);
    console.log(body);
    return res.json({ imageData: body});
});

现在response.imageData 是一个base64 编码字符串,您可以使用:data:image/png;base64,

请记住,您是在前端对 png 进行编码。如果您要使用不同的扩展程序,您可以从服务器发送完整的src

// 'content-type' must not be image/png or image/jpeg, improve the logic
// I'll leave that to you.
const src = `data:${response.headers['content-type']};base64,${body}`;

return res.json({ src });

另一种选择,是去掉ajax,直接发送图片,不用base64

正面

$("#resultImage").attr("src", "/test");

返回

app.get('/test', (req, res) => {
   let url = 'https://ion.gemma.feri.um.si/ion/services/geoserver/demo1/wms?service=WMS&version=1.1.0&request=GetMap&layers=demo1%3Amaribor-dof25&bbox=546631.6237364038%2C156484.86830455417%2C550631.7865026393%2C160485.0310707898&width=767&height=768&srs=EPSG%3A3794&format=image%2Fjpeg';

   request(url).pipe(res);
});

【讨论】:

    猜你喜欢
    • 2022-01-20
    • 2015-06-16
    • 2018-03-12
    • 2020-02-18
    • 1970-01-01
    • 2012-12-24
    • 2019-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多