MySQL是一种关系型数据库管理系统,用于存储和管理数据。在MySQL中添加数据通常涉及到向表中插入记录。上传图片并将其存储在数据库中通常涉及到以下几个步骤:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload Image</title>
</head>
<body>
<form id="uploadForm" enctype="multipart/form-data">
<input type="file" name="image" id="image">
<button type="submit">Upload</button>
</form>
<script>
document.getElementById('uploadForm').addEventListener('submit', function(event) {
event.preventDefault();
const formData = new FormData(this);
fetch('/upload', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
});
</script>
</body>
</html>
const express = require('express');
const multer = require('multer');
const mysql = require('mysql');
const path = require('path');
const app = express();
const upload = multer({ dest: 'uploads/' });
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'testdb'
});
db.connect(err => {
if (err) throw err;
console.log('Connected to MySQL database');
});
app.post('/upload', upload.single('image'), (req, res) => {
const imagePath = req.file.path;
const imageName = req.file.filename;
const sql = 'INSERT INTO images (name, path) VALUES (?, ?)';
db.query(sql, [imageName, imagePath], (err, result) => {
if (err) return res.status(500).send(err);
res.json({ message: 'Image uploaded successfully', id: result.insertId });
});
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
CREATE TABLE images (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
path VARCHAR(255) NOT NULL
);
enctype="multipart/form-data"
,或者后端未正确配置multer。enctype="multipart/form-data"
,后端正确配置multer。dest
配置,确保路径正确。通过以上步骤和代码示例,你可以实现一个基本的图片上传功能,并将图片信息存储到MySQL数据库中。
领取专属 10元无门槛券
手把手带您无忧上云