NodeJS 如何从MySQL中获取blob图像以响应组件

vaqhlq81  于 2023-02-18  发布在  Node.js
关注(0)|答案(1)|浏览(174)

我需要帮助从MySQL中获取我的blob图像到浏览器。我正在使用redux工具包。到目前为止,这些是我所拥有的。当我分派imageId时,我在Redux开发工具上得到isSuccess为true,但我似乎不知道如何将图像获取到我的浏览器。请帮助我解决这个问题。我卡住了。
谢谢

配置文件控制器.js上的控制器文件

const getProfilePicture = async (req, res) => {
  try {
    const base64Data = await ProfilePic.findByPk(req.params.imageId);
    res.send(base64Data);
  } catch (error) {
    res.status(500).send("error.message");
  }
};

当我点击控制器文件路由时,我在Postman上得到什么-数据库包含:::ID(imageId)、头像(Blob图像)、描述、创建时间、更新时间

{
  "id": "6dc38579-4e0f-4d4b-8777-7b6527408e72",
  "avatar": {
    "type": "Buffer",
    "data": [
      91,
      111,
      98,
      106,
      101,
      99,
      116,
      32,
      79,
      98,
      106,
      101,
      99,
      116,
      93
    ]
  },
  "description": null,
  "createdAt": "2023-02-17T09:22:28.000Z",
  "updatedAt": "2023-02-17T09:28:00.000Z"
}

getProfilePictureService.js上的服务文件

import axios from "axios";

const API_URL = "http://localhost:4000/api/profile/";

const getProfilePicture = async (imageId, token) => {
  const config = {
    headers: {
      Authorization: `Bearer ${token}`,
    },
    responseType: "arraybuffer",
  };
  try {
    const response = await axios.get(
      API_URL + "getProfilePicture/" + imageId,
      config
    );
    const imageBuffer = Buffer.from(response.data, "binary");
    const imageBlob = new Blob([imageBuffer], { type: "image/jpg" });
    return URL.createObjectURL(imageBlob);
  } catch (error) {
    console.log(error);
  }
};
const getProfilePictureService = {
  getProfilePicture,
};

export default getProfilePictureService;

获取配置文件图片切片.js上的切片文件

import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import getProfilePictureService from "./getProfilePictureService";

const initialState = {
  getProPics: [],
  isLoading: false,
  isSuccess: false,
  isError: false,
  message: "",
};

//get profile picture
export const getProfilePicture = createAsyncThunk(
  "profile/picture",
  async (imageId, thunkAPI) => {
    try {
      const token = thunkAPI.getState().auth.user.token;

      return await getProfilePictureService.getProfilePicture(imageId, token);
    } catch (error) {
      const message =
        (error.response &&
          error.response.data &&
          error.response.data.message) ||
        error.message ||
        error.toString();

      return thunkAPI.rejectWithValue(message);
    }
  }
);

export const getProfilePictureSlice = createSlice({
  name: "getProPic",
  initialState,
  reducers: {
    reset: (state) => initialState,
  },
  extraReducers: (builder) => {
    builder
      .addCase(getProfilePicture.pending, (state) => {
        state.isLoading = true;
      })
      .addCase(getProfilePicture.fulfilled, (state, action) => {
        state.isLoading = false;
        state.isSuccess = true;
        state.getProPics = action.payload;
      })
      .addCase(getProfilePicture.rejected, (state, action) => {
        state.isLoading = false;
        state.isError = true;
        state.message = action.payload;
      });
  },
});

export const { reset } = getProfilePictureSlice.actions;
export default getProfilePictureSlice.reducer;

我打算在其中使用图像ProfileBar.js的配置文件栏组件

import { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { getProfilePicture, reset } from "./features/getProfilePicture/getProfilePictureSlice";

const ProfileBar = ({ profile }) => {
  const dispatch = useDispatch();
  const [imageUrl, setImageUrl] = useState(null);
  const imageId = profile.id; //I placed the profile id (which is the same as the image primary key in the database) in a constant

  useEffect(() => {
    dispatch(getProfilePicture(imageId)); //I dispatch that id here. I get isSuccess to be true after dispatching
    return () => {
      dispatch(reset());
    };
  }, [dispatch]);

  useEffect(() => {
    async function fetchImage() {
      const url = await getProfilePicture(imageId);
      setImageUrl(url); //I intended to use this to set the state after dispatching and isSuccess is true
    }
    fetchImage();
  }, [imageId]);

  return (
    <div>
          <img src={imageUrl} alt="Image" /> //this is supposed to get the image on browser
    </div>
  );
};

export default ProfileBar;

相关问题