app.py<\/code> )<\/h3> import os\nfrom flask import Flask, request, render_template, send_from_directory\nfrom werkzeug.utils import secure_filename\n\n# Configure UPLOAD_FOLDER = 'uploads'\nALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif', 'docx'}\n\napp = Flask(__name__)\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\napp.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # Limit maximum upload of 16MB\n\n# Check whether the file extension allows def allowed_file(filename):\n return '.' in filename and \\\n filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\n\n@app.route('\/', methods=['GET', 'POST'])\ndef upload_file():\n if request.method == 'POST':\n # Check if there are files uploads if 'file' not in request.files:\n return 'No file part'\n file = request.files['file']\n # Check whether the user has selected the file if file.filename == '':\n return 'File not selected'\n # Security check and save if file and allowed_file(file.filename):\n filename = secure_filename(file.filename)\n file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n return render_template('upload.html', filename=filename)\n else:\n return 'Unsupported file types! '\n return render_template('upload.html')\n\n# Provide access route for uploaded files @app.route('\/uploads\/')\ndef uploaded_file(filename):\n return send_from_directory(app.config['UPLOAD_FOLDER'], filename)\n\nif __name__ == '__main__':\n # Makedirs(UPLOAD_FOLDER, exist_ok=True)\n app.run(debug=True)<\/pre>
3?? Running steps<\/h3> Install Flask:<\/p>
pip install flask<\/pre><\/li>
Create directories and files: <\/p>
- Create
uploads\/<\/code> directory<\/li>- Create
templates\/upload.html<\/code><\/li><\/ul><\/li> Run the application:<\/p>
python app.py<\/pre><\/li>
Open the browser to access: <\/p>
http:\/\/127.0.0.1:5000<\/pre>
\n ? Safety advice<\/h3>\n\n- Use
secure_filename()<\/code> to prevent path traversal attacks<\/li>\n- Limit file size (
MAX_CONTENT_LENGTH<\/code> )<\/li>\n- Verify file extension<\/li>\n
- Do not directly provide user file downloads in the production environment, it is recommended to add permission control.<\/li>\n<\/ul>\n
\n ? Optional enhancement features<\/h3>\n\n- File renaming (avoid overwriting):
filename = str(uuid.uuid4()) ext<\/code>\n<\/li>\n- Check file content type (MIME type)<\/li>\n
- Upload progress bar (need to cooperate with front-end JS)<\/li>\n
- Storage to cloud storage (such as S3, OSS)<\/li>\n<\/ul>\n
\n Basically that's all, this example is enough for learning and small to medium-sized projects. Simple but covers key points: forms, backend reception, secure processing, file saving and access.<\/p>"}
python flask upload file example
Jul 28, 2025 am 02:01 AM
The complete steps to implement file upload function in Flask are as follows: 1?? Create an HTML form containing file input fields and submit buttons, set enctype="multipart/form-data" to support file upload; 2?? Define routes in the Flask backend to process GET and POST requests, use request.files to obtain uploaded files, safely process the file name through secure_filename, and verify whether the file extension is in the allowable list. After confirming that it is correct, save the file to the specified directory, and set MAX_CONTENT_LENGTH to limit the upload size to enhance security; 3?? Provide upload file access routes, and use send_from_directory function to safely return files; 4?? Ensure that the project structure contains templates and uploads directories, and correctly install Flask dependencies; 5?? Run app.py to start the service and access the upload page through the browser to complete the test. The solution has covered basic uploads, security protection and file access, and is suitable for learning and small and medium-sized projects.

Implementing file uploading functions in Flask is very simple. Here is a complete, runnable example showing how to use Flask to receive files uploaded by users and save them to the specified directory of the server.

? Basic functions
- User uploads files through form
- Flask backend receives and saves files
- Prevent malicious file names (safe handling)
- Supports common file types (such as pictures, documents, etc.)
? Project structure
flask-upload/
│
├── app.py
├── uploads/ # The uploaded file will be saved here ├── templates/
│ └── upload.html # front-end page
<!DOCTYPE html>
<html>
<head>
<title>Upload file</title>
</head>
<body>
<h2>Upload file</h2>
<form method="POST" enctype="multipart/form-data">
<input type="file" name="file" required>
<button type="submit">Upload</button>
</form>
{% if filename %}
<p>Upload successfully! <a href="{{ url_for('uploaded_file', filename=filename) }}">View file</a></p>
{% endif %}
</body>
</html>
2?? Flask backend code ( app.py
)
import os
from flask import Flask, request, render_template, send_from_directory
from werkzeug.utils import secure_filename
# Configure UPLOAD_FOLDER = 'uploads'
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif', 'docx'}
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # Limit maximum upload of 16MB
# Check whether the file extension allows def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route('/', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
# Check if there are files uploads if 'file' not in request.files:
return 'No file part'
file = request.files['file']
# Check whether the user has selected the file if file.filename == '':
return 'File not selected'
# Security check and save if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return render_template('upload.html', filename=filename)
else:
return 'Unsupported file types! '
return render_template('upload.html')
# Provide access route for uploaded files @app.route('/uploads/<filename>')
def uploaded_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
if __name__ == '__main__':
# Makedirs(UPLOAD_FOLDER, exist_ok=True)
app.run(debug=True)
3?? Running steps
Install Flask:
pip install flask
Create directories and files:

- Create
uploads/
directory - Create
templates/upload.html
Run the application:
python app.py
Open the browser to access:

http://127.0.0.1:5000
? Safety advice
- Use
secure_filename()
to prevent path traversal attacks
- Limit file size (
MAX_CONTENT_LENGTH
)
- Verify file extension
- Do not directly provide user file downloads in the production environment, it is recommended to add permission control.
? Optional enhancement features
- File renaming (avoid overwriting):
filename = str(uuid.uuid4()) ext
- Check file content type (MIME type)
- Upload progress bar (need to cooperate with front-end JS)
- Storage to cloud storage (such as S3, OSS)
Basically that's all, this example is enough for learning and small to medium-sized projects. Simple but covers key points: forms, backend reception, secure processing, file saving and access.
The above is the detailed content of python flask upload file example. For more information, please follow other related articles on the PHP Chinese website!
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Polymorphism in python classes
Jul 05, 2025 am 02:58 AM
Polymorphism is a core concept in Python object-oriented programming, referring to "one interface, multiple implementations", allowing for unified processing of different types of objects. 1. Polymorphism is implemented through method rewriting. Subclasses can redefine parent class methods. For example, the spoke() method of Animal class has different implementations in Dog and Cat subclasses. 2. The practical uses of polymorphism include simplifying the code structure and enhancing scalability, such as calling the draw() method uniformly in the graphical drawing program, or handling the common behavior of different characters in game development. 3. Python implementation polymorphism needs to satisfy: the parent class defines a method, and the child class overrides the method, but does not require inheritance of the same parent class. As long as the object implements the same method, this is called the "duck type". 4. Things to note include the maintenance
Python Function Arguments and Parameters
Jul 04, 2025 am 03:26 AM
Parameters are placeholders when defining a function, while arguments are specific values ??passed in when calling. 1. Position parameters need to be passed in order, and incorrect order will lead to errors in the result; 2. Keyword parameters are specified by parameter names, which can change the order and improve readability; 3. Default parameter values ??are assigned when defined to avoid duplicate code, but variable objects should be avoided as default values; 4. args and *kwargs can handle uncertain number of parameters and are suitable for general interfaces or decorators, but should be used with caution to maintain readability.
Explain Python generators and iterators.
Jul 05, 2025 am 02:55 AM
Iterators are objects that implement __iter__() and __next__() methods. The generator is a simplified version of iterators, which automatically implement these methods through the yield keyword. 1. The iterator returns an element every time he calls next() and throws a StopIteration exception when there are no more elements. 2. The generator uses function definition to generate data on demand, saving memory and supporting infinite sequences. 3. Use iterators when processing existing sets, use a generator when dynamically generating big data or lazy evaluation, such as loading line by line when reading large files. Note: Iterable objects such as lists are not iterators. They need to be recreated after the iterator reaches its end, and the generator can only traverse it once.
Python `@classmethod` decorator explained
Jul 04, 2025 am 03:26 AM
A class method is a method defined in Python through the @classmethod decorator. Its first parameter is the class itself (cls), which is used to access or modify the class state. It can be called through a class or instance, which affects the entire class rather than a specific instance; for example, in the Person class, the show_count() method counts the number of objects created; when defining a class method, you need to use the @classmethod decorator and name the first parameter cls, such as the change_var(new_value) method to modify class variables; the class method is different from the instance method (self parameter) and static method (no automatic parameters), and is suitable for factory methods, alternative constructors, and management of class variables. Common uses include:
How to handle API authentication in Python
Jul 13, 2025 am 02:22 AM
The key to dealing with API authentication is to understand and use the authentication method correctly. 1. APIKey is the simplest authentication method, usually placed in the request header or URL parameters; 2. BasicAuth uses username and password for Base64 encoding transmission, which is suitable for internal systems; 3. OAuth2 needs to obtain the token first through client_id and client_secret, and then bring the BearerToken in the request header; 4. In order to deal with the token expiration, the token management class can be encapsulated and automatically refreshed the token; in short, selecting the appropriate method according to the document and safely storing the key information is the key.
What are Python magic methods or dunder methods?
Jul 04, 2025 am 03:20 AM
Python's magicmethods (or dunder methods) are special methods used to define the behavior of objects, which start and end with a double underscore. 1. They enable objects to respond to built-in operations, such as addition, comparison, string representation, etc.; 2. Common use cases include object initialization and representation (__init__, __repr__, __str__), arithmetic operations (__add__, __sub__, __mul__) and comparison operations (__eq__, ___lt__); 3. When using it, make sure that their behavior meets expectations. For example, __repr__ should return expressions of refactorable objects, and arithmetic methods should return new instances; 4. Overuse or confusing things should be avoided.
How does Python memory management work?
Jul 04, 2025 am 03:26 AM
Pythonmanagesmemoryautomaticallyusingreferencecountingandagarbagecollector.Referencecountingtrackshowmanyvariablesrefertoanobject,andwhenthecountreacheszero,thememoryisfreed.However,itcannothandlecircularreferences,wheretwoobjectsrefertoeachotherbuta
Describe Python garbage collection in Python.
Jul 03, 2025 am 02:07 AM
Python's garbage collection mechanism automatically manages memory through reference counting and periodic garbage collection. Its core method is reference counting, which immediately releases memory when the number of references of an object is zero; but it cannot handle circular references, so a garbage collection module (gc) is introduced to detect and clean the loop. Garbage collection is usually triggered when the reference count decreases during program operation, the allocation and release difference exceeds the threshold, or when gc.collect() is called manually. Users can turn off automatic recycling through gc.disable(), manually execute gc.collect(), and adjust thresholds to achieve control through gc.set_threshold(). Not all objects participate in loop recycling. If objects that do not contain references are processed by reference counting, it is built-in
See all articles