无法在 mongodb 中将图像存储为 base64 字符串

编程入门 行业动态 更新时间:2024-10-11 03:16:34

无法在 mongodb 中将图像存储为 base64 <a href=https://www.elefans.com/category/jswz/34/1771434.html style=字符串"/>

无法在 mongodb 中将图像存储为 base64 字符串

我想将图像作为字符串存储在 mongodb 中,但是当我发布数据时,字符串未存储,当我修改我的代码时,它给我 500 个内部服务器错误。我尝试先直接存储图像,但在 mongodb imageurl 字段中保持为空。所以我想将其转换为base64并将其存储在mongodb中

server.js

const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const cors = require('cors');
require('dotenv').config();
const { Buffer } = require('buffer');


const app = express();
const port = 5000;

// connect to MongoDB
mongoose.connect(process.env.DATABASE,{
  useNewUrlParser: true,
  useUnifiedTopology: true
}).then(() => console.log('DB Connected'));

// import the Candidate model
const Candidate = require('./candidate');

// use middleware
app.use(bodyParser.json());
app.use(cors());

// create a route for adding a candidate
app.post('/api/addcandidate', async (req, res) => {
  const { candidate_name, party_name, imageURL } = req.body;
  try {
    if (!imageURL) {
      throw new Error('Image URL is required');
    }
    const candidate = new Candidate({
      candidate_name,
      party_name,
      imageURL: Buffer.from(imageURL.split(",")[1], "base64").toString(),
    });
    await candidate.save();
    res.status(201).json({ message: 'Candidate added successfully' });
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Failed to add candidate' });
  }
});

app.get('/api/candidates', async (req, res) => {
  try {
    const candidates = await Candidate.find();
    res.status(200).json(candidates);
  } catch (error) {
    res.status(500).json({ message: 'Failed to get candidates' });
  }
});


// start the server
app.listen(port, () => {
  console.log(`Server listening on port ${port}`);
});

add.js

  const [data, setData] = useState({ candidate_name: "", party_name: "",  imageURL:"" });
  const [error, setError] = useState("");

  const handleChange = (event) => {
    if (event.target.name === "imageURL") {
      const file = event.target.files[0];
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onloadend = () => {
        setData({ ...data, [event.target.name]: reader.result });
      };
    } else {
      setData({ ...data, [event.target.name]: event.target.value });
    }
  };
  

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      const url = "http://localhost:5000/api/addcandidate";
      const { data: res } = await axios.post(url, data);
      localStorage.setItem("access_token", res.data);
      window.location = "/";
    } catch (error) {
      if (
        error.response &&
        error.response.status >= 400 &&
        error.response.status <= 500
      ) {
        setError(error.response.data.message);
      }
    }
  };
  

  return (
    <Container>
      <Logo>
        <img src="./amazon_logo.png" alt="" />
      </Logo>

      <FormContainer >
        <h3>Add Candidate</h3>

      
          />
        </InputContainer>

        <InputContainer>
          <p>ImageURL</p>
             <FileBase64
             type="file"
             multiple={false}
             onChange={handleChange}
             value={data.imageURL}
           />
          
        </InputContainer>

        <Button onClick={handleSubmit}>Add Candidate</Button>
      </FormContainer>
    </Container>
  );
}

回答如下:

更多推荐

无法在 mongodb 中将图像存储为 base64 字符串

本文发布于:2024-05-13 15:35:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1759884.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   中将   图像   mongodb

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!