flask前端上传excel文件
时间: 2023-10-07 19:13:19 浏览: 99
flask多文件上传
4星 · 用户满意度95%
在Flask中,可以使用Flask-WTF和Flask-Uploads扩展来实现前端上传Excel文件的功能。
1. 安装Flask-WTF和Flask-Uploads:
```
pip install Flask-WTF Flask-Uploads
```
2. 创建一个包含上传表单的HTML页面:
```html
<!DOCTYPE html>
<html>
<head>
<title>Upload Excel File</title>
</head>
<body>
<h1>Upload Excel File</h1>
<form method="POST" action="{{ url_for('upload') }}" enctype="multipart/form-data">
{{ form.csrf_token }}
{{ form.file }}
<input type="submit" value="Upload">
</form>
</body>
</html>
```
3. 创建Flask应用程序并配置Flask-Uploads:
```python
from flask import Flask, render_template
from flask_uploads import UploadSet, configure_uploads, ALL
from flask_wtf import FlaskForm
from wtforms import FileField
from wtforms.validators import DataRequired
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret_key'
app.config['UPLOADED_FILES_DEST'] = 'uploads'
app.config['UPLOADED_FILES_ALLOW'] = ALL
files = UploadSet('files', ALL)
configure_uploads(app, files)
class UploadForm(FlaskForm):
file = FileField('File', validators=[DataRequired()])
@app.route('/', methods=['GET', 'POST'])
def upload():
form = UploadForm()
if form.validate_on_submit():
filename = files.save(form.file.data)
return 'File uploaded: {}'.format(filename)
return render_template('upload.html', form=form)
if __name__ == '__main__':
app.run(debug=True)
```
4. 运行应用程序并在浏览器中访问上传表单页面:
```
python app.py
```
现在,你可以在表单中选择要上传的Excel文件并提交表单。如果上传成功,应用程序将返回“File uploaded: 文件名”。上传的文件将保存在“uploads”文件夹中。
阅读全文