spring 如何在react frontend中将byte[]转换为图像

ddrv8njm  于 2023-05-05  发布在  Spring
关注(0)|答案(2)|浏览(189)

我目前正在做一个涉及React前端和Sping Boot 后端的项目。作为这个项目的一部分,我需要创建的事件,包括细节和传单。当保存事件时,我将传单作为文件发送到后端,在那里它被转换为字节数组并成功保存。
现在,我面临着在前端显示图像的挑战。具体来说,我需要从后端检索字节数组并在前端显示图像。然而,到目前为止,我还不能这样做。
代码如下:

export default function EditEvent() {
  const { id } = useParams();
  let navigate = useNavigate();
  const [event, setEvent] = useState({
    eventName: "",
    eventType: "",
    eventLocationType: "",
  });
  const [location, setLocation] = useState("");
  const [startTime, setStartTime] = useState(moment());
  const [endTime, setEndTime] = useState(moment());
  const [selectedImage, setSelectedImage] = useState(undefined);
  const [imageUrl, setImageUrl] = useState(null);

  const { eventName, eventType, eventLocationType } = event;

  useEffect(() => {
    loadEvent();
  }, []);

  const loadEvent = async (e) => {
    const result = await axios.get(
      `http://localhost:8080/api/event/getEvent/${id}`
    );
    console.log(result.data);
    setEvent(result.data);
    setLocation(result.data.location);
    setStartTime(moment(result.data.startTime, "YYYY-MM-DDTHH:mm"));
    setEndTime(moment(result.data.endTime, "YYYY-MM-DDTHH:mm"));

    console.log(result.data.eventFlyer)
    const byteArray = result.data.eventFlyer;
    const blob = new Blob([byteArray], { type: "image/png" });
    console.log(blob)
    const imageUrl = URL.createObjectURL(blob);
    console.log(imageUrl);
    const img = new Image();
    img.onload = function () {
      console.log("Image loaded successfully.");
    };
    img.onerror = function (error) {
      console.log("Error loading image.", error);
    };
    img.src = imageUrl;
  };
useEffect(() => {
    if (selectedImage) {
      setImageUrl(URL.createObjectURL(selectedImage));
    }
  }, [selectedImage]);

return(
 <FormLabel disabled={true} align="left" sx={{ paddingBottom: "10px" }}>
          Event Flyer<span>(Optional)</span>
        </FormLabel>
        <div style={{ textAlign: "left", paddingBottom: "30px" }}>
          <input
            accept="image/*"
            type="file"
            id="select-image"
            style={{ display: "none" }}
            name="eventFlyer"
            onChange={(e) => setSelectedImage(e.target.files[0])}
          />
          <label htmlFor="select-image">
            <Button component="span" color="inherit">
              <CloudUploadOutlinedIcon sx={{ paddingRight: "10px" }} />
              Click to browse
            </Button>
          </label>
          {imageUrl && selectedImage && (
            <Box mt={2} textAlign="center">
              <div>Image Preview:</div>
              <img src={imageUrl} alt={selectedImage.name} height="100px" />
            </Box>
          )}
        </div>
)

这里我得到了console.log,
Error loading image. Event {isTrusted: true, type: 'error', target: img, currentTarget: img, eventPhase: 2, …}isTrusted: truebubbles: falsecancelBubble: falsecancelable: falsecomposed: falsecurrentTarget: nulldefaultPrevented: falseeventPhase: 0returnValue: truesrcElement: nulltarget: nulltimeStamp: 15488456.5type: "error"[[Prototype]]: Event
我刚刚检查了接收到的byte[]是否有效,是否使用Base64到图像转换器。它还显示byte[]是有效的,并正确显示图像。

UPDATE这是控制台显示的result.data

我将非常感谢任何可以帮助我克服这个问题并正确显示图像的建议或代码示例。提前感谢您的帮助。

fwzugrvs

fwzugrvs1#

fetch获得的JSON响应采用Base64编码,而不是原始字节数组。您可以考虑直接显示图像,而不是在结果前面加上data:image/jpeg;base64,,示例如下:

const [imageSrc, setImageSrc] = useState('');

const loadEvent = async (e) => {
  const result = await axios.get(
    `http://localhost:8080/api/event/getEvent/${id}`
  );
  setImageSrc('data:image/jpeg;base64,' + result.data.eventFlyer)
};

<img src={imageSrc} />
o7jaxewo

o7jaxewo2#

如果你有一个base64,你可以直接通过image标签来显示。这里是reference

相关问题