要使用 Flask 處理文件上傳,請按照以下步驟操作:
pip install Flask
pip install Werkzeug
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/upload', methods=['POST'])
def upload_file():
if 'file' not in request.files:
return 'No file part', 400
file = request.files['file']
if file.filename == '':
return 'No selected file', 400
if file:
# 保存文件到服務器的某個目錄
file.save('uploaded_files/' + file.filename)
return 'File uploaded and saved.', 200
if __name__ == '__main__':
app.run(debug=True)
templates 的文件夾,并在其中創建一個名為 index.html 的 HTML 文件,內容如下:<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>File Upload with Flask</title>
</head>
<body>
<h1>Upload a File</h1>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="Upload">
</form>
</body>
</html>
python app.py
現在,你可以訪問 http://localhost:5000/ 并嘗試上傳一個文件。上傳成功后,文件將保存在服務器的 uploaded_files 目錄中。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。