vue3+node+mysql实现图片上传,具体怎么实现,分别写前端和后端的例子代码
时间: 2024-04-08 13:31:09 浏览: 158
前端代码(Vue 3):
```vue
<template>
<div>
<input type="file" @change="handleFileUpload" />
<button @click="uploadImage">上传图片</button>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
selectedFile: null
};
},
methods: {
handleFileUpload(event) {
this.selectedFile = event.target.files[0];
},
uploadImage() {
const formData = new FormData();
formData.append('image', this.selectedFile);
axios.post('/api/upload', formData)
.then(response => {
console.log(response.data);
// 处理上传成功的逻辑
})
.catch(error => {
console.log(error);
// 处理上传失败的逻辑
});
}
}
};
</script>
```
后端代码(Node.js + Express + Multer + MySQL):
```javascript
const express = require('express');
const multer = require('multer');
const mysql = require('mysql');
const path = require('path');
const app = express();
// 配置Multer来处理文件上传
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'uploads/');
},
filename: (req, file, cb) => {
cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
}
});
const upload = multer({ storage });
// 配置MySQL数据库连接
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'your_database'
});
// 处理图片上传请求
app.post('/api/upload', upload.single('image'), (req, res) => {
const image = req.file.filename;
// 将图片信息插入数据库
connection.query('INSERT INTO images (image_path) VALUES (?)', [image], (error, results) => {
if (error) {
console.error(error);
res.sendStatus(500);
} else {
res.sendStatus(200);
}
});
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
```
请注意,上述代码仅供参考,你需要根据实际情况进行适当修改和调整。确保已安装所需的依赖库(axios、express、multer、mysql),并正确配置MySQL数据库连接信息和文件上传路径。
阅读全文