【问题标题】:SAP B1, How to display fetched Image from ItemImage?SAP B1,如何显示从 ItemImage 获取的图像?
【发布时间】:2020-01-17 21:14:08
【问题描述】:

我正在从 SAP B1 服务层获取图像。 在邮递员中,我可以将其视为image/png,但显示它时出现问题。

<img /> 中显示它的正确方法是什么?

require(fetchedImage) - 不起作用


我创建了一个云函数来获取图像并将其传递给客户端,但我不知道该怎么做。

有一个像这样的超级奇怪的物体

 data:
>     '�PNGörönöu001aönöu0000öu0000öu0000örIHDRöu0000öu.........

不知道如何通过res.send(IMAGE IN PNG) 传递它,所以我可以看到在客户端获取图像。

检查了base64 转换,但我不确定如何使用它们。


更新

邮递员请求:(这工作正常)

GET : https://su05.consensusintl.net/b1s/v1/ItemImages('test')/$value

标题:SessionId:尝试时问我

由于某种原因,我们无法直接在前端获取图像,需要创建一个中间件,所以我们在 Firebase Cloud Function 中进行操作

所以这里是获取图像但不知道如何传递它的函数。

这是 Firebase Cloud Function 中的函数:

if (!req.body.productId) {
      res.status(400).send({ error: "productId is required" });
      return;
    }

    console.log("Starting the process");

    const productId = req.body.productId;

    const login = await Auth.login();
    const fetchedImg = await ItemMaster.getImage(login["SessionId"], productId);

    //Here in the fetchedImg, we're getting some data like
    res
      .status(200)
      .set("Content-Type", "image/png")
      .send(fetchedImg);

我们收到这样的回复:

{状态:200,

状态文本:'OK',

标题:

{ server: 'nginx',

  date: 'Wed, 22 Jan 2020 03:52:22 GMT',

  'content-type': 'image/png',

  'transfer-encoding': 'chunked',

  connection: 'close',

  dataserviceversion: '3.0',

  'content-disposition': 'inline; filename="rr-96600.png"',

  vary: 'Accept-Encoding',

  'set-cookie': [ 'ROUTEID=.node2; path=/b1s' ] },

配置:

{ url:

数据:

'�PNG\r\n\u001a\n\u0000\u0000\u0000\rIHDR\u0000\u0000\u0000\u0000\u0000\u0000...\b\u0002\u0000\u0000\u0000\u0006\u001fS �\u0000\u0000\u0000\u0019tEXtSoftware\u0000Adobe ImageReadyq�e

这是超长的,还要多写 80-100 行

如果你想测试你可以使用以下:

邮递员:

发帖:https://us-central1-rapid-replacement.cloudfunctions.net/getImageFromItems

正文:{"productId":"test"}

有效的productId是:1.“RR000102”2.“test”3.“RR000101”

【问题讨论】:

  • 你有没有在后台设置内容类型res.set({'Content-Type': 'image/png'});
  • 是的,我也试过了,它的图像损坏了。
  • 你把它们保存在某个地方吗?
  • 不,我不是,没有那个有没有办法完成它?
  • 您可以直接代理它const request = require('request')和路由request.get(url).pipe(res);

标签: javascript node.js sapb1


【解决方案1】:

如果您想动态使用图像,则必须在组件安装后立即获取图像并在之后插入。然后应该将获取的图片保存在组件的状态中,并从那里包含在 img 标签的 src 属性中。假设您已经可以获取图片,下面的代码应该可以工作。

import React, { Component } from "react";

export default class ComponentWithFetchedImage extends Component {
  constructor() {
    super();
    this.state = { image: undefined };   
  }

  componentDidMount() {
    let fetch_url = "https://picsum.photos/200";   // Insert your fetch url here
    fetch(fetch_url)
      .then(res => res.blob())
      .then(blob => URL.createObjectURL(blob))
      .then(url => this.setState({ image: url }))
      .catch(err => console.log(err));
  }

  render() {
    return (
      <div className="component">
        <img src={this.state.image} alt="" />
      </div>
    );   
  }
}

【讨论】:

  • 我无法直接在 ComponentDidMount 中获取,因为我需要在服务器端创建一个自定义函数,为此,我正在通过 Cloud 函数进行。
  • 它不允许我在客户端获取,当我从 React 执行此操作时,它表示在 fetch / axios 中传递了非法标头。
【解决方案2】:

这是最接近我的工作解决方案。基本上,我尝试的是获取图像,然后将其转换为客户端上的 blob,以便您可以将其转换为 objectURL.Updated 代码将图像作为缓冲区流式传输并在客户端上使用,然后将其转换为 objectURL 和分配给图像 src

服务器代码:

const http = require('http')
const axios = require('axios')
const fs = require('fs')
const stream = require('stream')
const server = http.createServer(function(req, res) {
  if (req.url === '/') {


    res.setHeader("Access-Control-Allow-Origin", "*");
    axios.post(
      "https://su05.consensusintl.net/b1s/v1/ItemImages('test')/$value", {
        responseType: "blob"
      }).then(function(resp) {
      console.log(resp.data)
      const buf_stream = new stream.PassThrough()
      buf_stream.end(Buffer.from(resp.data))
      buf_stream.pipe(res.end())
    }).catch(err => console.log(err))
  }
})


server.listen(3500)

客户端代码:

<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <title></title>
</head>

<body>
  <img style="width:200px; height:200px" />
  <script>

  const img = document.getElementsByTagName("IMG")
  fetch('http://localhost:3500').then(function(response) {
    console.log(response)
    return response.body
  }).then(function(data) {
    console.log(data)
    const reader = data.getReader()
     return new ReadableStream({
    start(controller) {
      return pump();
      function pump() {
        return reader.read().then(({ done, value }) => {
          // When no more data needs to be consumed, close the stream
          if (done) {
              controller.close();
              return;
          }
          // Enqueue the next data chunk into our target stream
          controller.enqueue(value);
          return pump();
        });
      }
    }
  })
})
  .then(stream => new Response(stream))
  .then(response => response.blob())
  .then(blob => URL.createObjectURL(blob))
  .then(url => img[0].src = url)
  .catch(err => console.error(err));
    </script>
</body>

</html>

【讨论】:

  • 嘿,我忘了告诉你一件事,我确实在这里得到了一张图片GET : https://su05.consensusintl.net/b1s/v1/ItemImages('test')/$value,但是当我通过同样的事情时,它就不起作用了。如果您有更好的主意,请告诉我,如果打扰到您,请见谅。
  • 我的小小赞赏 :)
  • 查看更新的代码。这是我最后的尝试。希望你能找到解决办法。
【解决方案3】:

此问题已解决。

const getImage = async (sessionId, ItemCode) => {
  console.log("fetching image");
  let result = {};

  result = await axios.get(
    `${settings.url}${endpoints.ItemImages}('${ItemCode}')/$value`,
    { 
      headers: {Cookie: `B1SESSION=${sessionId}`},
      responseType: "arraybuffer" } 
    ).then(response => Buffer.from(response.data, 'binary').toString('base64'));

  //Here we're returning base64 value of Image
  return result;
};

所以我们可以在客户端使用

&lt;img src="data:image/png;base64,[BASE64-VALUE-HERE]"/&gt;

【讨论】:

    猜你喜欢
    • 2020-12-22
    • 2019-04-25
    • 2015-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-10
    • 1970-01-01
    相关资源
    最近更新 更多