flask上传图片到数据库
时间: 2023-06-24 10:06:28 浏览: 229
在 Flask 中上传图片到数据库,一般需要先将图片转换成二进制数据,再将其存储到数据库中。以下是一个简单的示例:
1. 安装必要的依赖:
```
pip install Flask
pip install Flask-MySQLdb
pip install Pillow
```
2. 创建 Flask 应用:
```python
from flask import Flask, request, jsonify, render_template
from flask_mysqldb import MySQL
from PIL import Image
import io
app = Flask(__name__)
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = 'password'
app.config['MYSQL_DB'] = 'test_db'
mysql = MySQL(app)
@app.route('/')
def home():
return render_template('index.html')
@app.route('/upload', methods=['POST'])
def upload():
image_file = request.files['image']
image = Image.open(io.BytesIO(image_file.read()))
# Convert image to binary data
img_byte_arr = io.BytesIO()
image.save(img_byte_arr, format='PNG')
img_byte_arr = img_byte_arr.getvalue()
cur = mysql.connection.cursor()
cur.execute("INSERT INTO images (image) VALUES (%s)", [img_byte_arr])
mysql.connection.commit()
cur.close()
return jsonify({'message': 'Image uploaded successfully!'})
if __name__ == '__main__':
app.run(debug=True)
```
3. 创建一个 HTML 表单,用于上传图片:
```html
<!DOCTYPE html>
<html>
<head>
<title>Upload Image</title>
</head>
<body>
<h1>Upload Image</h1>
<form action="{{ url_for('upload') }}" method="POST" enctype="multipart/form-data">
<input type="file" name="image">
<input type="submit" value="Upload">
</form>
</body>
</html>
```
4. 创建一个数据库表,用于存储图片:
```sql
CREATE TABLE images (
id INT(11) NOT NULL AUTO_INCREMENT,
image LONGBLOB NOT NULL,
PRIMARY KEY (id)
);
```
以上示例代码仅供参考,具体实现需要根据自己的需求进行修改。
阅读全文