我认为您需要向
Content-type
添加一个 'multipart/form-data'
标头,您还应该将图像文件附加为 'file'
而不是 'image'
,以便您的文件应像这样编辑:
let forms = document.querySelectorAll('form');
let divisionIdInput = form.querySelector('#divisionIdInput');
let imageInput = form.querySelector('#imageInput');
formData.append('file', imageInput.files[0], imageInput.files[0].name);
const divisionId = divisionIdInput.value;
fetch(`/divisionData/${divisionId}`, {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data',
},
body: formData,
})
.then(response => {
if (!response.ok) throw new Error('Error inserting data');
return response.text(); // Read the response as text
})
.then(responseText => {
console.log('Response from server:', responseText);
})
.catch(error => {
console.error('Error:', error);
});
你还应该将你的express函数包装在try-catch范围内,以发现后端的问题:
app.post('/divisionData/:divisionId', upload.single('image'), (req, res) => {
try{
const image = req.file.buffer;
const contentType = req.file.mimetype;
const { divisionId } = req.body;
// Check if any of the values are null
if (divisionId === undefined || image === undefined) {
res.send('All fields must have values.');
return;
}
const insert_user_query = "INSERT INTO divisions (divisionId, image, contentType) VALUES (?, ?, ?)";
const values = [divisionId, image, contentType];
conn.query(insert_user_query, values, (err, result) => {
if (err) {
console.error("Database error:", err);
return res.json({ error: "Failed while inserting data into database! Try to send files again." });
}
return res.json({ success: true });
});
}catch(err){
return res.status(500).json({ error: `Internal Server Error ${err}` });
}
});