如何在反应中将缓冲区数据显示为图像

发布于 2025-01-09 14:02:56 字数 897 浏览 4 评论 0原文

如何在react中显示图像。 ... ..

function App() {
  const [data, setData] = useState();
  useEffect(()=>{
    const getdata= async()=>{
    const response  = await axios.get('http://localhost:8000')
    setData(response.data)
    }getdata()
   }, [])
return (
  <div>
   {data && <img src={"data:image/jpg;base-64,"+data} alt='image'></img>}  
 </div>
 );
}

来自后端的后端

 const schema = mongoose.Schema({
    img:{data:Buffer,contentType:String},
    name:{type: String}
  })
 const imageModel = mongoose.model('images', schema)

 app.get("/", function(req, res, next) {
 imageModel.findOne({}, function(err, image) {
 if (err) { return next(err); }
  res.json(image.img.data);
  });
}); 

响应 https://i.sstatic.net/x4cSB.png

How to display image in react. ... ..

function App() {
  const [data, setData] = useState();
  useEffect(()=>{
    const getdata= async()=>{
    const response  = await axios.get('http://localhost:8000')
    setData(response.data)
    }getdata()
   }, [])
return (
  <div>
   {data && <img src={"data:image/jpg;base-64,"+data} alt='image'></img>}  
 </div>
 );
}

Backend

 const schema = mongoose.Schema({
    img:{data:Buffer,contentType:String},
    name:{type: String}
  })
 const imageModel = mongoose.model('images', schema)

 app.get("/", function(req, res, next) {
 imageModel.findOne({}, function(err, image) {
 if (err) { return next(err); }
  res.json(image.img.data);
  });
}); 

Response from backend https://i.sstatic.net/x4cSB.png

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

记忆消瘦 2025-01-16 14:02:56

您可以使用image.img.data.toString("base64")将缓冲区从数据库转换为base64表示形式。因此,您需要在后端进行以下更改:

app.get("/", function(req, res, next) {
  imageModel.findOne({}, function(err, image) {
  if (err) { return next(err); }

  // Replace the buffer array with base64 data
  const imgBase64 = image.img.data.toString("base64");
  image.img.data = imgBase64;

  // Send the object
  res.json(image.img);
});

you can use image.img.data.toString("base64") to convert the buffer from the database to base64 representation. So here is what you need to change in your backend:

app.get("/", function(req, res, next) {
  imageModel.findOne({}, function(err, image) {
  if (err) { return next(err); }

  // Replace the buffer array with base64 data
  const imgBase64 = image.img.data.toString("base64");
  image.img.data = imgBase64;

  // Send the object
  res.json(image.img);
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文