|
|
- import os
- from flask import Flask, request, redirect, url_for
- from werkzeug.utils import secure_filename
- UPLOAD_FOLDER = 'static/uploads' # Your upload directory
- ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
- app = Flask(__name__)
- 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':
- if 'file' not in request.files:
- return redirect(request.url)
- file = request.files['file']
- if file.filename == '':
- return redirect(request.url)
- if file and allowed_file(file.filename):
- filename = secure_filename(file.filename)
- # Corrected line: Join the UPLOAD_FOLDER with the filename
- file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
- return 'File uploaded successfully!'
- return '''
- <!doctype html>
- <title>Upload new File</title>
- <h1>Upload new File</h1>
- <form method=post enctype=multipart/form-data>
- <input type=file name=file>
- <input type=submit value=Upload>
- </form>
- '''
- if __name__ == '__main__':
- # Ensure the upload directory exists
- if not os.path.exists(UPLOAD_FOLDER):
- os.makedirs(UPLOAD_FOLDER)
- app.run(debug=True)
複製代碼
關鍵就在這一行:
- file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
複製代碼- app.config['UPLOAD_FOLDER']提供您指定的上傳目錄的路徑(例如,static/uploads)。
- 如果是在網域上需要絕對路徑才能上傳,不然無法正常上傳
- app.config["IMAGE_UPLOADS"] = os.path.join(os.path.dirname(__file__), 'static/uploads')
複製代碼
- filename是上傳文件的安全名稱。
- os.path.join()正確地將這兩部分結合起來,以建立出檔案應該儲存到的完整絕對路徑,包括檔案的名稱。
其他注意事項:
- 建立上傳目錄:
請先確認指定的目錄UPLOAD_FOLDER存在,然後再嘗試將檔案儲存到該目錄。 範例程式碼包含了對該目錄的檢查和建立過程。
- 安全的檔案名稱:
始終使用secure_filename()fromwerkzeug.utils來清理檔案名稱並防止目錄遍歷漏洞。
- 檔案權限:
請確保您的 Flask 應用程式對該UPLOAD_FOLDER目錄擁有必要的寫入權限。
Flask 在嘗試上傳圖片時出現的錯誤IsADirectoryError: [Errno 21] Is a directory表明,程式正在嘗試對目錄而非檔案執行檔案操作(例如儲存檔案)。 這種情況通常發生在file.save()上傳邏輯部分。
此錯誤最常見的原因是路徑不正確file.save()。 您可能提供了目錄路徑,但需要的是完整的檔案路徑(包括檔案名稱)。
|
|