upload上传文件代码
时间: 2023-12-02 17:57:08 浏览: 112
文件上传代码
以下是一个简单的Python Flask框架中使用的upload上传文件的示例代码:
```python
from flask import Flask, request, redirect, url_for
import os
app = Flask(__name__)
UPLOAD_FOLDER = '/path/to/folder' # 指定上传文件保存的路径
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif', 'csv'} # 允许上传的文件类型
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
def allowed_file(filename):
# 检查上传文件是否允许上传
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
# 获取上传文件
file = request.files['file']
# 如果选择了文件
if file and allowed_file(file.filename):
# 将文件保存至指定路径
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
# 上传完成后重定向至成功页面
return redirect(url_for('success'))
# 如果请求方式为 GET,则渲染前端页面供用户选择文件
return '''
<html>
<head>
<title>Upload new File</title>
</head>
<body>
<h1>Upload new File</h1>
<form method=POST enctype=multipart/form-data>
<input type=file name=file>
<input type=submit value=Upload>
</form>
</body>
</html>
'''
@app.route('/success')
def success():
return "File upload successful!"
```
注意:上传文件的路径和允许上传的文件类型需要根据实际情况进行修改。
阅读全文