Home > database >  Can we render InputStream from Spring Boot Backend on React Frontend?
Can we render InputStream from Spring Boot Backend on React Frontend?

Time:07-13

I have a virtual file system in my java spring boot backend that converts any file into an InputStream, I am sending this InputStream using REST to my React frontend. Is there anyway I can accordingly render this InputStream on the frontend?

This InputStream may be an text file, image file, xml file, etc.

CodePudding user response:

Sure. I've an example using axios.

  const readFile = async (filename: string) => {
    try {
      // fetch your file
      const response = await axios.get(`/api/file/${filename}`, {
        responseType: "arraybuffer",
      });

      // read your response into a blob
      const file = new Blob([response.data], {
        type: "text/plain",
      });

      // read your blob as text
      const reader = new FileReader();
      reader.onload = () => {
        alert(reader.result);
      };
      reader.readAsText(file);
    } catch (e) {

      // error handling
      console.error(e);
    }
  };

If you have an image you would want to use URL.createObjectURL:

      const file = new Blob([response.data], {
        type: "image/png",
      });
      const objectURL = URL.createObjectURL(file);
      myImage.src = objectURL;
  • Related