当我将图像上传到我的网站时,它会将图像发送到后端以将图像上传到 mongodb 数据库,我将图像的 base64 上传到数据库,但问题是有时当我取回图像。 例如:
(3) [{…}, {…}, {…}]
0
:
photo
:
"false"
__v
:
0
_id
:
"650ce3fb077e8bd7795561e0"
[[Prototype]]
:
Object
1
:
photo
:
"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEASABIAA
__v
:
0
_id
:
"650ce411077e8bd7795561e4"
[[Prototype]]
:
Object
2
:
photo
:
"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEASABIAA
__v
:
0
_id
:
"650ce413077e8bd7795561e6"
[[Prototype]]
:
Object
length
:
3
这里第一个照片数据是“假”,获取时没有任何显示,但其他两个有数据。 另外,当我尝试再次上传它时,有时它可以正常工作。 这是“uploadImage”代码:
import express from 'express';
import * as dotenv from 'dotenv';
import Image from '../mongodb/models/image.js';
dotenv.config();
const router = express.Router();
router.route('/').get(async (req, res) => {
try {
await Image.find({}).then( data => {
res.status(200).json({ success: true, data: data });
});
} catch (err) {
console.log(err)
res.status(500).json({ success: false, message: 'Fetching posts failed, please try again' });
}
});
router.route('/').post(async (req, res) => {
try {
const {base64} = req.body;
await Image.create({
photo: base64,
});
res.status(200).json({ success: true});
} catch (err) {
console.log(err)
res.status(500).json({ success: false, message: 'Unable to upload the image, please try again' });
}
});
export default router;
在react中上传图像代码:
const handleImageUpload = async (e) => {
const file = e.target.files[0];
var reader = new FileReader();
reader.readAsDataURL(file)
reader.onload =() => {
// base 64
// console.log(reader.result)
SetImage(reader.result)
}
reader.onerror = e => {
console.log("Reader Error " , e)
}
if (file) {
const imageUrl = URL.createObjectURL(file);
setForm({ ...form, file, photo: imageUrl });
try {
const response = await fetch('http://localhost:8080/api/v1/uploadImage', {
method: 'POST',
headers: {
"Content-Type": "application/json",
Accept : "application/json",
"Access-Control-Allow-Origin": "*",
},
body: JSON.stringify({
base64 : image
}),
});
console.log(response);
if (response.ok) {
console.log('Image uploaded and saved successfully!');
} else {
console.error('Failed to upload image');
}
} catch (error) {
console.error('Error uploading image:', error);
}
};
}
所以我找到了一个奇怪的解决方案 问题出在这行代码中: ` const base64Data = wait readFileAsync(file);
SetImage(base64Data);`
有时,即使条件成立,图像 base64 也不会保存在“图像”状态。 所以我像这样将base64直接发送到api:
if (file) {
const imageUrl = URL.createObjectURL(file);
setForm({ ...form, file, photo: imageUrl });
try {
const base64Data = await readFileAsync(file);
const response = await fetch('http://localhost:8080/api/v1/uploadImage', {
method: 'POST',
headers: {
"Content-Type": "application/json",
Accept : "application/json",
"Access-Control-Allow-Origin": "*",
},
body: JSON.stringify({
base64 : base64Data
}),
});
并且成功了。