在云服务器上上传图片到数据库通常涉及以下几个步骤:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload Image</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="image">
<button type="submit">Upload</button>
</form>
</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: 'your_host',
user: 'your_user',
password: 'your_password',
database: 'your_database'
});
db.connect(err => {
if (err) throw err;
console.log('Connected to the database!');
});
app.post('/upload', upload.single('image'), (req, res) => {
const imagePath = path.join(__dirname, req.file.path);
const sql = 'INSERT INTO images (path) VALUES (?)';
db.query(sql, [imagePath], (err, result) => {
if (err) throw err;
res.send('Image uploaded and saved to database!');
});
});
app.listen(3000, () => {
console.log('Server started on http://localhost:3000');
});
通过以上步骤和代码示例,你可以在云服务器上实现图片上传并存储到数据库的功能。
领取专属 10元无门槛券
手把手带您无忧上云