200字范文,内容丰富有趣,生活中的好帮手!
200字范文 > Ajax+Python flask实现上传文件功能

Ajax+Python flask实现上传文件功能

时间:2021-11-21 04:38:23

相关推荐

Ajax+Python flask实现上传文件功能

HTML:

<div ><input type="file" name="FileUpload" id="FileUpload"><a class="layui-btn layui-btn-mini" id="btn_uploadimg">上传图片</a></div>

Ajax实现:

<script type="text/jscript">$(function () {$("#btn_uploadimg").click(function () {var fileObj = document.getElementById("FileUpload").files[0]; // js 获取文件对象if (typeof (fileObj) == "undefined" || fileObj.size <= 0) {alert("请选择图片");return;}var formFile = new FormData();formFile.append("action", "UploadVMKImagePath"); formFile.append("file", fileObj); //加入文件对象//第一种 XMLHttpRequest 对象//var xhr = new XMLHttpRequest();//xhr.open("post", "/Admin/Ajax/VMKHandler.ashx", true);//xhr.onload = function () {// alert("上传完成!");//};//xhr.send(formFile);//第二种 ajax 提交var data = formFile;$.ajax({url: "/upload/",data: data,type: "Post",dataType: "json",cache: false,//上传文件无需缓存 processData: false,//用于对data参数进行序列化处理 这里必须false contentType: false, //必须 success: function (result) {alert("上传完成!");},})})})</script>

后台flask:

from flask import Flask,render_template,request,redirect,url_forfrom werkzeug.utils import secure_filenameimport osfrom flask import send_from_directoryfrom werkzeug import SharedDataMiddlewareUPLOAD_FOLDER = '/uploads' #文件存放路径ALLOWED_EXTENSIONS = set(['jpg']) #限制上传文件格式app = Flask(__name__)app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDERapp.config['MAX_CONTENT_LENGTH'] = 5 * 1024 * 1024

def allowed_file(filename):

return '.' in filename and \

filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/upload/', methods=['GET', 'POST'])def upload_file():if request.method == 'POST':# check if the post request has the file partif 'file' not in request.files:flash('No file part')return redirect(request.url)file = request.files['file']# if user does not select file, browser also# submit an empty part without filenameif file.filename == '':flash('No selected file')return redirect(request.url)if file and allowed_file(file.filename):filename = secure_filename(file.filename)file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))return '{"filename":"%s"}' % filenamereturn ''

以上基本上就可以实现上传功能了。

以下是对界面样式,就是选择文件的那个上传按钮样式做了一些修改

如下图:

HTML:此处还添加了文件格式限制,只能选择.torrent 文件

<div class="divcenter" style="width:1025px"><div style="width:100%;height:600px"><div id="div_torrent" style="overflow:hidden"><a id="btn_file" href="javascript:;" class="file" style="margin-top:5px;margin-bottom:5px;float:left;">选择文件<input type="file" name="FileUpload" id="FileUpload" accept=".torrent"></a><div id="showFileName" style="float:left;margin-top:7px;margin-bottom:5px;"></div><input id="btn_upload" type="button" value="上传" onclick="onsubmit" class="file" style="float:right;width:65px; height: 33px;left: 4px;background-color:rgba(255, 206, 68, 0.6);cursor:hand;margin-top:5px;margin-bottom:5px;margin-right:5px;border-color:red" /></div></div></div>

CSS样式:

.file {position: relative;display: inline-block;background: #D0EEFF;border: 1px solid #99D3F5;border-radius: 4px;padding: 4px 12px;overflow: hidden;color: #1E88C7;text-decoration: none;text-indent: 0;line-height: 20px;}.file input {position: absolute;font-size: 100px;right: 0;top: 0;opacity: 0;}.file:hover {background: #AADFFD;border-color: #78C3F3;color: #004974;text-decoration: none;}

以上代码选择文件后,不会显示文件名,所以需要添加一个事件:

<script type="text/jscript">$(function () {$("#btn_file").on("change","input[type='file']",function(){var filePath=$(this).val();if(filePath.indexOf("torrent")!=-1){var arr=filePath.split('\\');var fileName=arr[arr.length-1];$("#showFileName").html(fileName);}else{$("#showFileName").html("");}})})</script>

上传的代码没做修改:此处增加了一个最大文件大小限制 5Mb

<script type="text/jscript">$(function () {$("#btn_upload").click(function () {var fileObj = document.getElementById("FileUpload").files[0]; // js 获取文件对象if (typeof (fileObj) == "undefined" || fileObj.size <= 0|| $("#showFileName").html()=="") {alert("请选择BT种子");return;}if(fileObj.size>5242880){alert("BT种子限制最大 5Mb");return;}var formFile = new FormData();formFile.append("action", "UploadTorrentPath");formFile.append("file", fileObj); //加入文件对象//第一种 XMLHttpRequest 对象//var xhr = new XMLHttpRequest();//xhr.open("post", "/Admin/Ajax/VMKHandler.ashx", true);//xhr.onload = function () {// alert("上传完成!");//};//xhr.send(formFile);//第二种 ajax 提交var data = formFile;$.ajax({url: "/upload/",data: data,type: "Post",dataType: "json",cache: false,//上传文件无需缓存processData: false,//用于对data参数进行序列化处理 这里必须falsecontentType: false, //必须success: function (result) {alert("上传完成!");},error: function (xmlrequest, textStatus, errorThrown) {alert("上传失败!");//alert("error:" + textStatus + errorThrown + ":" + JSON.stringify(xmlrequest));console.log("error:" + textStatus + errorThrown + ":" + JSON.stringify(xmlrequest));}})})})</script>

PS.喜欢看动漫的同学,可以来我的网站下载动漫哦

参考文章1:/LoveTX/p/7081515.html

参考文章2:/post/css_input_uploadmh

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。