vue2上传图片并预览、py、flask_mysqld将路径写入数据库
时间: 2024-10-16 09:05:11 浏览: 39
在Vue 2中,上传图片并预览通常会使用`vue-file-preview`这样的库来实现在组件内展示图片。步骤如下:
1. 安装依赖:
```bash
npm install vue-file-preview axios
```
2. 在组件中:
- 设置input[type=file]事件监听,获取选择的文件。
- 使用`FileReader`读取文件并转换为Base64格式。
- 预览Base64图片,显示在组件模板上。
```html
<template>
<div>
<input type="file" @change="uploadImage" />
<img :src="previewUrl" v-if="previewUrl" />
</div>
</template>
<script>
import FilePreview from 'vue-file-preview';
export default {
components: { FilePreview },
data() {
return {
file: null,
previewUrl: '',
};
},
methods: {
uploadImage(e) {
const files = e.target.files;
if (files.length > 0) {
this.file = files[0];
this.previewUrl = this.getFileBase64(this.file);
}
},
getFileBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onerror = reject;
reader.readAsDataURL(file);
});
},
},
};
</script>
```
3. Flask + MySQLdb中将图片路径写入数据库:
- 安装Flask和MySQLdb库:
```bash
pip install flask mysqlclient
```
- Python代码示例:
```python
from flask import Flask, request, jsonify
import pymysql
app = Flask(__name__)
conn = pymysql.connect(host='your_host', user='your_user', password='your_password', db='your_db')
@app.route('/upload', methods=['POST'])
def upload_image():
file = request.files['image']
with open('temp.jpg', 'wb') as f:
f.write(file.read())
try:
cursor = conn.cursor()
sql = "INSERT INTO images (path) VALUES ('%s')" % ('temp.jpg',)
cursor.execute(sql)
conn.commit()
cursor.close()
return jsonify({'message': 'Success'})
except Exception as e:
conn.rollback()
return jsonify({'error': str(e)})
if __name__ == '__main__':
app.run(debug=True)
```
阅读全文