当前位置:网站首页>Upload and download filask files
Upload and download filask files
2022-07-24 23:45:00 【Clean night mortal dust】
Methods to introduce
use Flask Handling file uploads is easy , Just make sure you don't forget in your HTML Set... In the form enctype=“multipart/form-data” Properties will do . Otherwise, the browser will not transfer your file .
Uploaded files are stored in memory or in a temporary location on the file system . You can request objects by files Property to access the uploaded file . Every uploaded file is stored in this Dictionary type attribute . This attribute is basic and standard Python file object , One more Used to save uploaded files to the file system of the server save() Method
If you want to know the name of the file in the client system before uploading , have access to filename attribute . But keep in mind that this value is Can be forged , Never trust this value . If you want to use the file name of the client as the file name on the server , Can pass Werkzeug Provided secure_filename() function
Of uploaded files html
The following code has ‘/upload’ URL The rules , The rule is in templates The folder shows ‘upload.html’, as well as ‘/upload-file’ URL The rules , Used to invoke uploader() Function to handle the upload process .
‘upload.html’ There is a file selector button and a submit button
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>File upload</title>
</head>
<body>
<form action="http://localhost:5000/uploader" method="POST" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value=" Submit ">
</form>
</body>
</html>

Upload files
After selecting files , Click Submit .
Form post Method call ‘/upload_file’ URL.
The underlying function uploader() Perform save operation .
from flask import Flask, render_template, request
from werkzeug.utils import secure_filename
import os
app = Flask(__name__)
# Define the storage path of uploaded files , There must be a peer directory upload
app.config['UPLOAD_FOLDER'] = 'upload/'
# Set the upload size to 16M
# app.config['MAX_CONTENT_LENGTH']=16 * 1000 * 1000
@app.route('/upload')
def upload_file():
return render_template('upload.html')
@app.route('/uploader', methods=['GET', 'POST'])
def uploader():
if request.method == 'POST':
f = request.files['file']
print(request.files)
f.save(os.path.join(app.config['UPLOAD_FOLDER'], secure_filename(f.filename)))
return 'file uploaded successfully'
else:
return render_template('upload.html')
if __name__ == '__main__':
app.run(debug=True)

Download the file
We need to provide services for uploaded files , Enable it to be downloaded by users . We will define a download_file View to provide services for uploading files in the folder , url_for(“download_file”, name=name) Generate download according to the file name URL
from flask import send_from_directory
@app.route('/download/<name>')
def download_file(name):
return send_from_directory(app.config["UPLOAD_FOLDER"], name,as_attachment=True)

complete python Code
from flask import Flask, render_template, request, send_from_directory
from werkzeug.utils import secure_filename
import os
app = Flask(__name__)
# Define the storage path of uploaded files , There must be a peer directory upload
app.config['UPLOAD_FOLDER'] = 'upload/'
# Set the upload size to 16M
# app.config['MAX_CONTENT_LENGTH']=16 * 1000 * 1000
@app.route('/upload')
def upload_file():
return render_template('upload.html')
@app.route('/uploader', methods=['GET', 'POST'])
def uploader():
if request.method == 'POST':
f = request.files['file']
print(request.files)
f.save(os.path.join(app.config['UPLOAD_FOLDER'], secure_filename(f.filename)))
return 'file uploaded successfully'
else:
return render_template('upload.html')
@app.route('/download/<name>')
def download_file(name):
return send_from_directory(app.config['UPLOAD_FOLDER'], name, as_attachment=True)
if __name__ == '__main__':
app.run(debug=True)
边栏推荐
- Solve the problem that JSP cannot use session.getattribute()
- Do you need to open an account to buy a wealth management product with a 6% income?
- 基于TensorFlow和Keras的卷积神经网络实现猫狗数据集分类实验
- Browser cache
- I'd like to ask if the table creation DDL of ODPs can't be directly executed in MySQL. The string type is incompatible. Can you only adjust this by yourself
- Use and partial explanation of QDIR class
- Pit record: typeerror:'module'object is not callable
- Cross entropy loss
- Piziheng embedded: the method of making source code into lib Library under MCU Xpress IDE and its difference with IAR and MDK
- Code coverage
猜你喜欢

Old Du servlet JSP

Weekly summary (*66): next five years

Add a little surprise to life and be a prototype designer of creative life -- sharing with X contestants in the programming challenge

Notes of Teacher Li Hongyi's 2020 in-depth learning series 9

2022 the most NB JVM foundation to tuning notes, thoroughly understand Alibaba P6 small case

Opengauss kernel analysis: query rewriting

多线程&高并发(全网最新:面试题 + 导图 + 笔记)面试手稳心不慌

Be an artistic test / development programmer and slowly change yourself

91. (leaflet chapter) leaflet situation plotting - offensive direction drawing

How to put long links into Excel
随机推荐
Shell echo command
Are you still using system. Currenttimemillis()? Take a look at stopwatch
Which securities account is the best and safest for beginners
Network Security Learning (II) IP address
See project code Note 1
把字符串转换成整数与不要二
Excel file processing tool class (based on easyexcel)
P3201 [hnoi2009] dream pudding heuristic merge
Implementation of cat and dog data set classification experiment based on tensorflow and keras convolutional neural network
Financial products can reach 6%. I want to open an account to buy financial products
[nuxt 3] (x) runtime configuration
Simple message queue implementation nodejs + redis =mq
JS ------ Chapter 3 JS cycle
I'd like to ask if the table creation DDL of ODPs can't be directly executed in MySQL. The string type is incompatible. Can you only adjust this by yourself
Shardingsphere database sub database sub table introduction
Notes of Teacher Li Hongyi's 2020 in-depth learning series 7
Only by learning these JMeter plug-ins can we design complex performance test scenarios
必会面试题:1.浅拷贝和深拷贝_深拷贝
你还在使用System.currentTimeMillis()?来看看StopWatch吧
Be an artistic test / development programmer and slowly change yourself