字符串"/>
无法在 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 字符串
发布评论