日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

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

發布時間:2025/7/14 python 45 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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_for from werkzeug.utils import secure_filename import os from flask import send_from_directory from werkzeug import SharedDataMiddlewareUPLOAD_FOLDER = '/uploads' #文件存放路徑 ALLOWED_EXTENSIONS = set(['jpg']) #限制上傳文件格式app = Flask(__name__) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER app.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.喜歡看動漫的同學,可以來我的網站下載動漫哦? www.wikibt.com

參考文章1:https://www.cnblogs.com/LoveTX/p/7081515.html

參考文章2:https://www.haorooms.com/post/css_input_uploadmh

?

轉載于:https://www.cnblogs.com/mqxs/p/10295250.html

總結

以上是生活随笔為你收集整理的Ajax+Python flask实现上传文件功能的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。