Python?flask使用ajax上傳文件的示例代碼
前言
JS
為什么要用ajax來提交
在使用from提交時(shí),瀏覽器會(huì)向服務(wù)器發(fā)送選中的文件的內(nèi)容而不僅僅是發(fā)送文件名。
為安全起見,即file-upload 元素不允許 HTML 作者或 JavaScript 程序員指定一個(gè)默認(rèn)的文件名。HTML value 屬性被忽略,并且對(duì)于此類元素來說,value屬性是只讀的,這意味著只有用戶可以輸入一個(gè)文件名。當(dāng)用戶選擇或編輯一個(gè)文件名時(shí),file-upload 元素觸發(fā) onchange 事件句柄。
利用form提交會(huì)導(dǎo)致頁面刷新,體驗(yàn)不好,所以使用AJAX進(jìn)行文件上傳是個(gè)不錯(cuò)的選擇。但這需要我們自己來組織通過POST請(qǐng)求發(fā)送的內(nèi)容
FormData對(duì)象
通過FormData對(duì)象可以組裝一組用 XMLHttpRequest發(fā)送請(qǐng)求的鍵/值對(duì)。它可以更靈活方便的發(fā)送表單數(shù)據(jù),因?yàn)榭梢元?dú)立于表單使用。如果你把表單的編碼類型設(shè)置為multipart/form-data ,則通過FormData傳輸?shù)臄?shù)據(jù)格式和表單通過submit() 方法傳輸?shù)臄?shù)據(jù)格式相同。 —— MDN web docs
Form的enctype屬性
enctype這個(gè)屬性管理的是表單的MIME編碼,它一共有三個(gè)屬性:
值 | 描述 |
---|---|
application/x-www-form-urlencoded | 在發(fā)送前編碼所有字符(默認(rèn)) |
multipart/form-data | 不對(duì)字符編碼,用來制定傳輸數(shù)據(jù)的特殊類型,如mp3、jpg |
text/plain | 純文本傳輸 |
Input
value | 保存了用戶指定的文件的名稱 |
---|---|
type=“file” | 設(shè)置input類型為file |
multiple=“multiple” | 可多選,不設(shè)置為單選 |
accept=“…” | 設(shè)置可選文件的MIME_type。在設(shè)置之后點(diǎn)擊選擇文件按鈕會(huì)默認(rèn)顯示符合設(shè)置的MIME_type的文件(存在兼容性)。具體的文件類型對(duì)應(yīng)的MIME類型可以搜索到,這里列出我用到的類型: |
MIME類型(更多直接百度,類型超乎你的想想)
文件類型 | MIME類型 |
---|---|
.txt | text/plain |
application/pdf | |
.doc | application/msword |
.docx | application/vnd.openxmlformats-officedocument.wordprocessingml.document |
.xls | application/vnd.ms-excel |
.ppt | application/vnd.ms-powerpoint |
.pptx | application/vnd.openxmlformats-officedocument.presentationml.presentation |
上傳單個(gè)文件
html代碼部分
<form id="uploadForm" method="post" enctype="multipart/form-data"> <label >上傳電子書</label> <input type="file" name="file" > <button id="upload" type="button" name="button" >上傳</button> </br> </br> </br> </form>
javascript代碼部分
<script src="http://www.jq22.com/jquery/jquery-1.10.2.js"></script> <script src="https://cdn.bootcdn.net/ajax/libs/layer/3.5.1/layer.js "></script> <script> $("#upload").click(function(){ var formData = new FormData($('#uploadForm')[0]); $.ajax({ type: 'post', url: "{{ url_for('.regression_report') }}", //上傳文件的請(qǐng)求路徑必須是絕對(duì)路勁 data: formData, cache: false, processData: false, contentType: false, success:function(data){ // 這里是訪問成功時(shí)被自動(dòng)執(zhí)行的代碼 // 拆分返回值信息(具體返回什么東西就看視圖函數(shù)中定義的json格式) status_ret = data.status; errmsg_ret = data.errmsg; layer.msg(errmsg_ret); switch (status_ret){ case 0: setTimeout(function(){window.location.href = "{{ url_for('.regression_report') }}";},"2000"); break default: setTimeout(function(){window.location.href = "{{ url_for('.regression_report') }}";},"2000"); break } }, error:function(jqXHR){ // 這里是訪問失敗時(shí)被自動(dòng)調(diào)用的代碼 } }); }); </script>
當(dāng)你的頁面樣式比較多的時(shí)候,可能上述方法無法傳入文件,下面這種方法比較強(qiáng),推薦看看
<form class="info" method="post" enctype="multipart/form-data"> <div class="form-group"> <label>File upload</label> <input id="id_regression_html" type="file" name="regression_html" class="file-upload-default"> <div class="input-group col-xs-12"> <input type="text" class="form-control file-upload-info" disabled="" placeholder="Upload Regression.html"> <span class="input-group-append"> <button id="html_upload" class="file-upload-browse btn btn-gradient-primary" type="button">Html Upload</button> </span> </div> </div> <button id="id_ajax_submit" type="button" class="btn btn-gradient-primary mr-2">Submit</button> </form>
<script src="https://cdn.bootcdn.net/ajax/libs/layer/3.5.1/layer.js "></script> <script> $("#id_ajax_submit").click(function(){ // var formData = new FormData($('#uploadForm')[0]); let formData = new FormData(); let my_file = document.getElementById('id_regression_html'); // @Param: <input name="regression_html"> // @Param: myFile.file[0]為第一個(gè)文件(單選),多個(gè)文件(多選)則要循環(huán)添加 formData.append('regression_html',my_file.files[0]); $.ajax({ type: 'post', url: "{{ url_for('.regression_report') }}", //上傳文件的請(qǐng)求路徑必須是絕對(duì)路勁 data: formData, cache: false, async: false, processData: false, //告訴jquery不要處理發(fā)送的數(shù)據(jù) contentType: false, //告訴jquery不要設(shè)置content-Type請(qǐng)求頭 success:function(data){ // 這里是訪問成功時(shí)被自動(dòng)執(zhí)行的代碼 // 拆分返回值信息(具體返回什么東西就看視圖函數(shù)中定義的json格式) status_ret = data.status; errmsg_ret = data.errmsg; layer.msg(errmsg_ret); switch (status_ret){ case 0: setTimeout(function(){window.location.href = "{{ url_for('.regression_report') }}";},"2000"); break case 1: setTimeout(function(){window.location.href = "{{ url_for('.regression_report') }}";},"2000"); break default: setTimeout(function(){window.location.href = "{{ url_for('.regression_report') }}";},"2000"); break } }, error:function(jqXHR){ // 這里是訪問失敗時(shí)被自動(dòng)調(diào)用的代碼 } }); }); </script>
flask 視圖函數(shù)部分
@admin_blu.route("/toolReg", methods=['GET', 'POST']) def regression_report(): if request.method == "GET": return render_template('index.html') elif request.method == "POST": # TODO: 獲取設(shè)置 # TODO: 獲取文件 f = request.files.get('file') if f and f.filename.__contains__('.html'): upload_path = os.path.join(current_app.root_path, 'static/upload/html', f.filename) download_path = os.path.join(current_app.root_path, 'static/upload/html', 'xlsx') # TODO: 類實(shí)例化,同步執(zhí)行 f.save(upload_path) ret = { "status": 0, "errmsg": "上傳成功" } return jsonify(ret) return redirect(url_for(".index.html"))
上傳多個(gè)文件
html
<form id="uploadForm" enctype="multipart/form-data"> <input type="file" name="file" multiple="multiple" /> </form> <button id="btnUpload">上傳文件</button>
js
<script> $("#btnUpload").on("click", function(){ var formdata = new FormData($("#uploadForm")[0]); alert(formdata); $.ajax({ type: "post", url: "/Attendance/UploadFile2/",//url地址 contentType: false, cache: false, processData: false, data: formdata, success: function (data) { console.log(data); } }); }); </script>
出問題解決方案
//將formdata改用下面的方式試下 var formdata = new FormData(); var files = $("input[type='file']")[0].files; for (var i = 0; i < files.length; i++) { formdata.append("file", files[i]); }
到此這篇關(guān)于Python flask使用ajax上傳文件的文章就介紹到這了,更多相關(guān)Python flask上傳文件內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python?Socket實(shí)現(xiàn)遠(yuǎn)程木馬彈窗詳解
這篇文章主要介紹了Python?Socket實(shí)現(xiàn)遠(yuǎn)程木馬彈窗詳解,Socket用來描述IP地址和端口,是通信鏈的句柄,應(yīng)用程序可以通過Socket向網(wǎng)絡(luò)發(fā)送請(qǐng)求或者應(yīng)答網(wǎng)絡(luò)請(qǐng)求2022-07-07Python正則表達(dá)re模塊之findall()函數(shù)詳解
在python中,通過內(nèi)嵌集成re模塊可以直接調(diào)用來實(shí)現(xiàn)正則匹配,其中re.findall()函數(shù)可以遍歷匹配,可以獲取字符串中所有匹配的字符串,返回一個(gè)列表,這篇文章主要給大家介紹了關(guān)于Python正則表達(dá)re模塊之findall()函數(shù)的相關(guān)資料,需要的朋友可以參考下2022-07-07Python中列表元素轉(zhuǎn)為數(shù)字的方法分析
這篇文章主要介紹了Python中列表元素轉(zhuǎn)為數(shù)字的方法,結(jié)合實(shí)例形式對(duì)比分析了Python列表操作及數(shù)學(xué)運(yùn)算的相關(guān)技巧,需要的朋友可以參考下2016-06-06關(guān)于python tushare Tkinter構(gòu)建的簡(jiǎn)單股票可視化查詢系統(tǒng)(Beta v0.13)
這篇文章主要介紹了python tushare Tkinter構(gòu)建的簡(jiǎn)單股票可視化查詢系統(tǒng)(Beta v0.13),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-10-10Flask框架踩坑之a(chǎn)jax跨域請(qǐng)求實(shí)現(xiàn)
這篇文章主要介紹了Flask框架踩坑之a(chǎn)jax跨域請(qǐng)求實(shí)現(xiàn),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2019-02-02利用Python演示數(shù)型數(shù)據(jù)結(jié)構(gòu)的教程
這篇文章主要介紹了利用Python演示數(shù)型數(shù)據(jù)結(jié)構(gòu)的教程,核心代碼其實(shí)只有一行(XD),需要的朋友可以參考下2015-04-04Python values()與itervalues()的用法詳解
今天小編就為大家分享一篇Python values()與itervalues()的用法詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-11-11