首页 > 解决方案 > 使用 base64 在客户端显示图像的问题

问题描述

我正在尝试上传图像并使用base 64在客户端显示它。我成功地发送到mongodb,但在上传后没有显示图像。

我的理论:我需要在 setGetBaseFile 函数之外有 setDefaultImage 函数来修复,以便能够在客户端看到图像。当我尝试移动它时,我得到一个“错误:重新渲染太多。React 限制了渲染的数量以防止无限循环。我发现解决此错误的唯一方法是将函数移回父函数中.

下面是我的 image.js 代码

const mongoose = require("mongoose");
const Image = mongoose.model("gallery");
const express = require('express');
const ImageRouter = express.Router();
const DIR = './public/';

/*  upload image in base64 format, thereby, directly storing it in mongodb datanase
    along with images uploaded using firebase storage  */    

    ImageRouter.route("/uploadbase")
    .post((req, res, next) => {
        const newImage = new Image({
            imageName: req.body.imageName,
            imageData: req.body.imageData
        });

        newImage.save()
            .then((result) => {
                res.status(200).json({
                    success: true,
                    document: result
                });
            })
            .catch((err) => next(err));
    });

module.exports = ImageRouter;

下面是我的客户端代码:

import React, { useState } from "react";

import Container from "react-bootstrap/Container";
import Card from "react-bootstrap/Card";
// import Button from "react-bootstrap/Button";
// import "./postverse.css";
import Form from "react-bootstrap/Form";
import axios from "axios";

import FileBase from 'react-file-base64';
import DefaultImg from '../../assets/default-image.jpg';

const GlobalPost = () => {
  
  const API_URL = "http://localhost:5000";
  const [baseImage, UseBaseImage] = useState(DefaultImg);
  const [DefaultImage, setDefaultImage] = useState("");

// function to upload image once it has been captured
  setDefaultImage({
    baseImage: DefaultImg
  });

  // function to capture base64 format of an image
  function setGetBaseFile(files) {
    // create a local readable base64 instance of an image

    UseBaseImage({
      baseImage: files.base64
    });  

    let imageObj = {
      imageName: "base-image-" + Date.now(),
      imageData: files.base64.toString()
    };

    axios.post(`${API_URL}/image/uploadbase`, imageObj)
      .then((data) => {
        if (data.data.success) {
          alert("Image has been successfully uploaded using base64 format");
          UseBaseImage("base")
        }
      })
      .catch((err) => {
        alert("Error while uploading image using base64 format")
        UseBaseImage("base") 
      });
    }


  return (
    <div className="globalpost">
      <Container className="mt-5 ml-auto mr-auto">
        <h1 className="text-center">
          Post to
          <span className="text-success"> ShareVerse</span>
        </h1>
        <Form
          className="shadow p-3 mb-5 bg-white rounded"
          action="/search"
          method="post"
          encType="multipart/form-data"
        >
          <Form.Group controlId="formBasicVerse">
            <Form.Label><h5>Upload Image</h5></Form.Label>
            <FileBase type="file" 
                      multiple={false} 
                      onDone={setGetBaseFile} 
            />
            <Card.Img src={baseImage} alt="upload-image"></Card.Img>
          </Form.Group>
        </Form>
      </Container>
    </div>
  );
};

export default GlobalPost;

下面是我的猫鼬 data.schema

const mongoose = require("mongoose");

//create schema
const ImagesSchema = new mongoose.Schema({
  name: {
    type: String,
    default: "none",
    required: true
  },
  imageData: {
    // type: mongoose.Types.ObjectId,
    type: String,
    required: true,
  },
});

module.exports = mongoose.model("gallery", ImagesSchema);

下面是我的 app.js

// file includes all app level config, middleware, and supporting libraries

const express = require("express"); //import express
const app = express(); //initalise app with express
const cors = require("cors");
const bodyParser = require("body-parser");
const logger = require("morgan");
const routes = require("./routes/DataRoutes");
const ImageRouter = require('./routes/image');


app.use(bodyParser.json());
//body-parser handles HTTP POST requests.
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
//enable Cross-Origin Resource Sharing.
app.use(cors());

app.use(express.json());
// get log details of our app if needed
app.use(logger("dev"));

//middleware to import routes
app.use('/image', ImageRouter);
app.use("/", routes);


app.use('/search', express.static('search'));

module.exports = app;

标签: javascriptnode.jsreactjsexpress

解决方案


推荐阅读