简体   繁体   English

在javascript前端显示来自Spring boot后端的图像文件

[英]Display an image file from Spring boot backend in javascript front end

Can anyone guide me how to get the image data from the spring boot backend to a react front end?.谁能指导我如何从 Spring Boot 后端获取图像数据到 React 前端? Im basically saving the file in the server and by using the path saved in the db ill be retrieving the image.我基本上将文件保存在服务器中,并通过使用保存在数据库中的路径来检索图像。

So far I managed to get the file as an byte array to the front end and it can be checked in the network.到目前为止,我设法将文件作为字节数组发送到前端,并且可以在网络中进行检查。 I need help displaying it in a <img/> Thank you我需要帮助在<img/>显示它谢谢

Recently worked on this topic.最近在研究这个话题。 Sharing my experience分享我的经验

React反应

const [imageData, setImageData] = React.useState({});

  const getImage = (url) => {
    axios.get(url).then((response) => {
      setImageData(response);
    });
  };

  const displayImage = () => {
    return (
      <div className="img">
        <img
          src={`data:image/jpeg;base64,${imageData}`}
          alt=""
        />
      </div>
    );
  };

Controller控制器

@GetMapping("/{id}")
    public ResponseEntity<byte[]> getFile(@PathVariable Long id) {
       FileObject fileObject =  fileRepository.findById(id).get();
       byte[] base64encodedData = Base64.getEncoder().encode(fileObject.getData());
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + 
                 fileObject.getName() + "\"")
                .body(base64encodedData);
    }

Note : It is important that the image data is Base64 encoded in the Server注意:重要的是图像数据在服务器中是 Base64 编码的

Base64.getEncoder().encode(fileObject.getData())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM