問題描述
Flask 文件上傳失敗並出現 404 錯誤 (Flask File Upload fails with 404 error)
在遵循有關如何上傳文件的 Flask 文檔/教程時,我使用了以下代碼:
main.py:
try:
# import python modules
import sys
import config
import os
import inspect
import datetime
from flask import Flask,render_template,jsonify,redirect,url_for,request
from werkzeug import secure_filename
except ImportError as e:
print "Import error:", e, "\nAborting the program", __version__
sys.exit()
app = Flask(__name__)
app.config.from_object('config.BaseConfig')
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
@app.route("/upload", methods=['POST'])
def upload():
if request.method == 'POST':
file = request.files['file']
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
filename = os.path.join(app.config['CSV_FOLDER'], filename)
return jsonify({"success": "True", "post": "none"})
else:
return jsonify({"success": "False", "post": "Invalid filename"})
else:
return jsonify({"success": "False", "post": "POST request required!"})
config.py:
class BaseConfig(object):
DEBUG = True
TESTING = False
PROPAGATE_EXCEPTIONS = True
SECRET_KEY = ""
CSV_FOLDER = "static/csv"
當在我的 Windows 機器上的 localhost 上運行時,上面的效果很好。當我將它上傳到我的 Hostmonster 站點時,我得到一個 404 http‑status‑code(找不到頁面)。
這是我的 Hostmonster .htaccess 文件(存儲在 /GKS 中):
AddHandler fcgid‑script .fcgi
RewriteEngine On
RewriteBase /GKS
RewriteCond %{REQUEST_FILENAME} !‑f
RewriteRule ^(.*)$ gks.fcgi/$1 [QSA,L]
這是我在 Hostmonster 網站上的文件夾結構圖片:Hostmonster 文件夾結構 如果我查看瀏覽器開發控制台,我會看到這個 add'l 錯誤消息:“ 主線程上的同步 XMLHttpRequest 已被棄用,因為它會對最終用戶的體驗產生不利影響。如需更多幫助,請查看 https://xhr.spec.whatwg.org/。"。不確定如果這與我的文件上傳有任何關係。
請幫忙,因為我正在努力解決這個問題。
參考解法
方法 1:
I finally found my problem! I used the url '/upload' in my Javascript. For whatever reason that worked in the Localhost development environment, but not on the live site. When I changed that to 'upload' all is well.
Hope this will help someone in the future.
(by Volker Petersen、Volker Petersen)