python3实现web文件上传功能的小demo
基于flask实现
效果图:

实现代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import os
import uuid
import platform
from flask import Flask, request, redirect, url_for
from werkzeug.utils import secure_filename

if platform.system() == "Windows":
slash = '\\'
else:
platform.system() == "Linux"
slash = '/'
UPLOAD_FOLDER = 'upload'
ALLOW_EXTENSIONS = set(['html', 'htm', 'doc', 'docx', 'mht', 'pdf'])
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
if not os.path.exists(UPLOAD_FOLDER):
os.makedirs(UPLOAD_FOLDER)
else:
pass


def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1] in ALLOW_EXTENSIONS


@app.route('/', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
file = request.files['file']
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file_name = str(uuid.uuid4()) + '.' + filename.rsplit('.', 1)[1]
file.save(os.path.join(app.config['UPLOAD_FOLDER'], file_name))
base_path = os.getcwd()
file_path = base_path + slash + app.config['UPLOAD_FOLDER'] + slash + file_name
print(file_path)
return redirect(url_for('upload_file', filename=file_name))
return '''
<!doctype html>
<title>Upload new File</title>
<h1>Upload new File</h1>
<form action="" method=post enctype=multipart/form-data>
<p><input type=file name=file>
<input type=submit value=Upload>
</form>
'''


if __name__ == "__main__":
app.run(host='0.0.0.0', port=50000)

代码为很早之前网上公开的一份demo,感觉写的还不错,就保存了下来,最近整理文件的时候无意中发现了这个小demo,但是遗憾的是找不到原文了只找到了一堆Ctrl+C的文章,作者如果看到可联系我进行添加转载原文地址。