Flask文件上传功能出现404错误,请求排查解决
Let’s break down the most likely issues causing your 404 errors and fix them step by step:
1. Missing Server Startup Code
Looking at your main.py, there’s no code to actually launch the Flask server! Flask needs an explicit trigger to start running. Add this block at the bottom of main.py:
if __name__ == '__main__': # Debug mode helps catch errors with detailed messages app.run(debug=True)
If you prefer using the flask run terminal command instead, first set the required environment variable:
- On Windows Command Prompt:
set FLASK_APP=main.py - On Windows PowerShell:
$env:FLASK_APP = "main.py"
Then runflask run—it will start the server athttp://localhost:5000by default.
2. Verify Your Project Folder Structure
Flask expects templates to live in a templates folder, and your upload directory needs to exist (and be properly configured). Double-check your project matches this structure:
your_project/ ├── main.py ├── app.py # Must contain `app = Flask(__name__)` to create the Flask instance ├── templates/ │ ├── index.html │ ├── uploaded.html │ ├── map.html │ └── contact.html └── uploads/ # Create this folder manually for file uploads
Also, add the upload folder configuration to app.py (you’re referencing app.config['UPLOAD_FOLDER'] but haven’t set it yet):
import os from flask import Flask app = Flask(__name__) # Define the upload folder path relative to your project root app.config['UPLOAD_FOLDER'] = os.path.join(app.root_path, 'uploads')
3. Why localhost:5500 Returns 404
Flask’s default port is 5000—there’s nothing in your code that would launch the server on port 5500 unless you explicitly specify it. If you want to use 5500, update the startup code:
if __name__ == '__main__': app.run(port=5500, debug=True)
Or run flask run --port 5500 after setting the FLASK_APP variable.
4. Double-Check Route Access
Your routes look correct, but confirm you’re accessing the right URLs:
- Visit
http://localhost:5000/orhttp://localhost:5000/upload(both map to the same view) - Ensure the
appimported fromapp.pyis the actual Flask instance (no typos in variable names)
Enabling debug mode (debug=True) will also help you catch other hidden issues (like missing template files) with detailed browser error messages instead of generic 404s.
内容的提问来源于stack exchange,提问作者Lorenzo Castagno

