python怎么实现文件上传界面

Python (190) 2023-06-20 13:36:41

本文章代码上传在码云上

代码地址

git@gitee.com:DanYuJie/upanddown.git

这里我们使用flask框架,简单实用

目录结构:
upandown/
static/
css/
js/
jquery.min.js
toastr.min.js
templates/
index.html
test.py

相关推荐:《Python基础教程》

首先我们需要一个页面在templates/index.html(这里使用form表单实现)

<!DOCTYPEhtml>
<html>
<head>
<metacharset="UTF-8">
<metaname="viewport"content="width=device-width,initial-scale=1.0">
<metahttp-equiv="X-UA-Compatible"content="ie=edge">
<linkrel="stylesheet"href="../static/css/toastr.min.css">
<scriptsrc="../static/js/jquery.min.js"></script>
<scriptsrc="../static/js/toastr.min.js"></script>
<title>Document</title>
</head>
<body>
<formmethod="POST"action="/upload"enctype="multipart/form-data">
<inputtype="file"name="file"id="file">
<inputtype="submit"value="upload">
<ahref=""></a>
</form><hr>
<olid="filelist">
</ol>
<script>
functioncheckstatus(){
if('{{status}}'=='OK'){
toastr['success']("上传成功");
}elseif('{{status}}'=='null'){
toastr['error']("上传失败");
}
}
functionget_list(){
$.ajax({
url:'/getlist',
type:'GET',
success:function(result){
len_result=result.length;
for(varx=0;x<len_result;x++){
$("#filelist").append('<br><ahref=/download/'+result[x]+'>'+result[x]
+'</a>');
}
alert(content_list);
},
error:function(){
alert("失败");
}
});
}
checkstatus();
get_list();
</script>
</body>
</html>

然后是后台接收

test.py

#!/usr/bin/envpython
#-*-coding:utf-8-*-
fromflaskimportFlask,render_template,request,send_from_directory,jsonify,redirect
importos
#importsys
#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'
defallow_file(filename):
allow_list=['png','PNG','jpg','doc','docx','txt','pdf','PDF','xls','rar','exe','md','zip']
a=filename.split('.')[1]
ifainallow_list:
returnTrue
else:
returnFalse
@app.route('/main')
defhome():
returnrender_template('index.html')
@app.route('/getlist')
defgetlist():
file_url_list=[]
file_floder=app.config['UPLOAD_FOLDER']+'/upload'
file_list=os.listdir(file_floder)
forfilenameinfile_list:
file_url=url_for('download',filename=filename)
file_url_list.append(file_url)
#printfile_list
returnjsonify(file_list)
@app.route('/download/<filename>')
defdownload(filename):
returnsend_from_directory(download_floder,filename,as_attachment=True)
@app.route('/upload',methods=['POST','GET'])
defupload():
file=request.files['file']
ifnotfile:
returnrender_template('index.html',status='null')
#printtype(file)
ifallow_file(file.filename):
file.save(os.path.join(app.config['UPLOAD_FOLDER']+'/upload/',file.filename))
returnrender_template('index.html',status='OK')
else:
return'NO'
if__name__=='__main__':
app.run(debug=True,host='0.0.0.0')
THE END

发表回复