Python使用Flask框架同时上传多个文件的方法
作者:niuniu 发布时间:2023-02-02 10:16:49
标签:Python,Flask,框架,上传,文件
本文实例讲述了Python使用Flask框架同时上传多个文件的方法,分享给大家供大家参考。具体如下:
下面的演示代码带有详细的html页面和python代码
import os
# We'll render HTML templates and access data sent by POST
# using the request object from flask. Redirect and url_for
# will be used to redirect the user once the upload is done
# and send_from_directory will help us to send/show on the
# browser the file that the user just uploaded
from flask import Flask, render_template, request, redirect, url_for, send_from_directory
from werkzeug import secure_filename
# Initialize the Flask application
app = Flask(__name__)
# This is the path to the upload directory
app.config['UPLOAD_FOLDER'] = 'uploads/'
# These are the extension that we are accepting to be uploaded
app.config['ALLOWED_EXTENSIONS'] = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
# For a given file, return whether it's an allowed type or not
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1] in app.config['ALLOWED_EXTENSIONS']
# This route will show a form to perform an AJAX request
# jQuery is loaded to execute the request and update the
# value of the operation
@app.route('/')
def index():
return render_template('index.html')
# Route that will process the file upload
@app.route('/upload', methods=['POST'])
def upload():
# Get the name of the uploaded files
uploaded_files = request.files.getlist("file[]")
filenames = []
for file in uploaded_files:
# Check if the file is one of the allowed types/extensions
if file and allowed_file(file.filename):
# Make the filename safe, remove unsupported chars
filename = secure_filename(file.filename)
# Move the file form the temporal folder to the upload
# folder we setup
file.save(os.path.join(app.config['UPLOAD_FOLDER'],filename))
# Save the filename into a list, we'll use it later
filenames.append(filename)
# Redirect the user to the uploaded_file route, which
# will basicaly show on the browser the uploaded file
# Load an html page with a link to each uploaded file
return render_template('upload.html', filenames=filenames)
# This route is expecting a parameter containing the name
# of a file. Then it will locate that file on the upload
# directory and show it on the browser, so if the user uploads
# an image, that image is going to be show after the upload
@app.route('/uploads/<filename>')
def uploaded_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'],
filename)
if __name__ == '__main__':
app.run(
host="0.0.0.0",
port=int("80"),
debug=True
)
index.html代码
<!DOCTYPE html>
<html lang="en">
<head>
<link href="bootstrap/3.0.0/css/bootstrap.min.css"
rel="stylesheet">
</head>
<body>
<div class="container">
<div class="header">
<h3 class="text-muted">How To Upload a File.</h3>
</div>
<hr/>
<div>
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" multiple="" name="file[]" class="span3" /><br/>
<input type="submit" value="Upload" class="span2">
</form>
</div>
</div>
</body>
</html>
upload.html页面:
<!DOCTYPE html>
<html lang="en">
<head>
<link href="bootstrap/3.0.0/css/bootstrap.min.css"
rel="stylesheet">
</head>
<body>
<div class="container">
<div class="header">
<h3 class="text-muted">Uploaded files</h3>
</div>
<hr/>
<div>
This is a list of the files you just uploaded, click on them to load/download them
<ul>
{% for file in filenames %}
<li><a href="{{url_for('uploaded_file', filename=file)}}">{{file}}</a></li>
{% endfor %}
</ul>
</div>
<div class="header">
<h3 class="text-muted">Code to manage a Upload</h3>
</div>
<hr/>
<pre>
@app.route('/upload', methods=['POST'])
def upload():
# Get the name of the uploaded file
#file = request.files['file']
uploaded_files = request.files.getlist("file[]")
filenames = []
for file in uploaded_files:
# Check if the file is one of the allowed types/extensions
if file and allowed_file(file.filename):
# Make the filename safe, remove unsupported chars
filename = secure_filename(file.filename)
# Move the file form the temporal folder to the upload
# folder we setup
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
filenames.append(filename)
# Redirect the user to the uploaded_file route, which
# will basicaly show on the browser the uploaded file
# Load an html page with a link to each uploaded file
return render_template('upload.html', filenames=filenames)
</pre>
</div>
</div>
</body>
</html>
希望本文所述对大家的Python程序设计有所帮助。


猜你喜欢
- layer弹出窗口在弹出时指定了area,弹出后,如果当前页面(iframe)大小比弹出的窗口小,那么就会出现无法操作弹出窗口的尴尬情况。如
- 什么是LangChain?使用ChatGPT大家可能都是知道prompt, (1)想像一下,如果我需要快速读一本书,想通过本书作为
- 桥接模式Bridge Pattern是什么桥接模式是一种结构型模式,它将抽象部分与实现部分分离开来,使它们可以独立地变化。在桥接模式中,我们
- 前言需要从数据库检索某些符合要求的数据,我们很容易写出 Select A B C FROM T WHERE ID = XX 这样
- 一、散点图散点图用两组数据构成多个坐标点,考察坐标点的分布,判断两变量之间是否存在某种关联或总结坐标点的分布模式。特点:判断变量之间是否存在
- 1. 用grep函数 函数名 grep 调用语法 @foundlist = grep (pattern, @searchlist); 解说
- 哲学上有种说法,“运动是绝对的,静止是相对的”。我们在编写各样的效果时,时常会碰到动画。下面的章,将讨论动画的原理以及实现。动画,简而言之就
- 有时候会碰到需求,将字典来反转,即:字典中的键作为值,而字典中的值作为键。对于字典比较小,可以使用普通方法方法一:使用普通方法转换>&
- Windows下的分隔符默认的是逗号,而MAC的分隔符是分号。拿到一份用分号分割的CSV文件,在Win下是无法正确读取的,因为CSV模块默认
- 前言plt.contour是python中用于画等高线的函数,这里介绍一下plt.contour的使用。使用示例import numpy a
- 简介在很多实际的项目开发中,我们需要实现很多实时功能;而在这篇文章中,我们就利用django channels简单地实现了点对点聊天和消息推
- 最近几天,学习python3的对FTP操作,做下总结!!!!1.FTP链接这样写的好处就是如果报错,很快就能找到错在哪里,方便找到问题。2.
- match()函数的使用。以及从文本中提取数据的方法。在学习re模块的相关函数前应了解正则表达式的特殊字符准备一个要爬取的文本文档:直接从某
- 我们常常看到一个这样的表达式 A=lambda x:x+1可能会一头雾水不知道怎么计算 最基本的理解就是def A(x):retu
- sys模块sys.argv: 实现从程序外部向程序传递参数。位置参数argv[0]代表py文件本身,运行方法 python xx.py 参数
- 一、基本概念(查询语句)①基本语句1、“select * from 表名;”,—
- 问题参考自:https://www.zhihu.com/question/440066129/answer/1685329456 ,mysq
- 本文实例讲述了Python使用add_subplot与subplot画子图操作。分享给大家供大家参考,具体如下:子图:就是在一张figure
- 泰勒展开与e的求法大家伙儿知道计算机里的 e是怎么求出来的吗?这还要从神奇的泰勒展开讲起……简单
- 前言Python语言的turtle库是一个直观有趣的图形绘制函数库,是python语言标准库之一。turtle库也叫海龟库,是turtle绘