引言
图片上传
1.1 前端实现
<template>
<div>
<input type="file" @change="handleFileChange" />
</div>
</template>
<script>
export default {
methods: {
handleFileChange(event) {
const file = event.target.files[0];
if (file) {
this.uploadImage(file);
}
},
uploadImage(file) {
// 这里可以添加上传图片的逻辑,例如使用axios发送请求到后端API
}
}
}
</script>
1.2 后端实现
const express = require('express');
const multer = require('multer');
const path = require('path');
const app = express();
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/');
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
}
});
const upload = multer({ storage: storage });
app.post('/upload', upload.single('image'), (req, res) => {
res.send('Image uploaded successfully');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
图片存储
2.1 选择合适的数据库
- 存储容量:根据图片数量和大小选择合适的存储容量。
- 读写性能:考虑数据库的读写性能,以满足业务需求。
- 扩展性:选择易于扩展的数据库,以便未来业务发展。
2.2 数据库设计
以下是一个简单的数据库设计示例,使用MySQL数据库:
CREATE TABLE images (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255),
path VARCHAR(255),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
2.3 数据库操作
在Vue3项目中,可以使用axios等HTTP客户端库来实现与数据库的交互。以下是一个使用axios和MySQL的示例:
import axios from 'axios';
const API_URL = 'http://localhost:3000/api';
const uploadImageToDatabase = async (file) => {
const formData = new FormData();
formData.append('image', file);
try {
const response = await axios.post(`${API_URL}/upload`, formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
});
console.log('Image uploaded successfully', response.data);
} catch (error) {
console.error('Error uploading image', error);
}
};
图片展示
3.1 前端展示
<template>
<div>
<img :src="imagePath" alt="Image" />
</div>
</template>
<script>
export default {
data() {
return {
imagePath: ''
};
},
mounted() {
this.fetchImage();
},
methods: {
fetchImage() {
// 这里可以添加获取图片路径的逻辑,例如从数据库中查询
}
}
}
</script>
3.2 后端展示
const express = require('express');
const fs = require('fs');
const path = require('path');
const app = express();
app.get('/image/:id', (req, res) => {
const imagePath = path.join(__dirname, 'uploads', req.params.id);
fs.readFile(imagePath, (err, data) => {
if (err) {
res.status(404).send('Image not found');
} else {
res.setHeader('Content-Type', 'image/jpeg');
res.send(data);
}
});
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});