这篇文章将为大家详细讲解有关python实现文件上传界面的方法,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

网站建设哪家好,找创新互联!专注于网页设计、网站建设、微信开发、微信小程序定制开发、集团企业网站建设等服务项目。为回馈新老客户创新互联还提供了慈利免费建站欢迎大家使用!
本文章代码上传在码云上
代码地址
git@gitee.com:DanYuJie/upanddown.git
这里我们使用flask框架,简单实用
目录结构: upandown/ static/ css/ js/ jquery.min.js toastr.min.js templates/ index.html test.py
首先我们需要一个页面在templates/index.html(这里使用form表单实现)
Document
然后是后台接收
test.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from flask import Flask,render_template, request, send_from_directory,jsonify, redirect
import os
# import sys
# reload(sys)
# sys.setdefaultencoding('utf-8')
app = Flask(__name__)
# ALLOWED_EXTENSTIONS = set(['png', 'jpg', 'jpeg', 'gif'])
app.config['UPLOAD_FOLDER'] = os.getcwd()
download_floder = app.config['UPLOAD_FOLDER'] + '/upload'
def allow_file(filename):
allow_list = ['png', 'PNG', 'jpg', 'doc', 'docx', 'txt', 'pdf', 'PDF', 'xls', 'rar', 'exe', 'md', 'zip']
a = filename.split('.')[1]
if a in allow_list:
return True
else:
return False
@app.route('/main')
def home():
return render_template('index.html')
@app.route('/getlist')
def getlist():
file_url_list = []
file_floder = app.config['UPLOAD_FOLDER'] + '/upload'
file_list = os.listdir(file_floder)
for filename in file_list:
file_url = url_for('download',filename=filename)
file_url_list.append(file_url)
# print file_list
return jsonify(file_list)
@app.route('/download/')
def download(filename):
return send_from_directory(download_floder,filename, as_attachment=True)
@app.route('/upload', methods=['POST', 'GET'])
def upload():
file = request.files['file']
if not file:
return render_template('index.html', status='null')
# print type(file)
if allow_file(file.filename):
file.save(os.path.join(app.config['UPLOAD_FOLDER']+'/upload/', file.filename))
return render_template('index.html', status='OK')
else:
return 'NO'
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0') 关于python实现文件上传界面的方法就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。