目錄
前言
JS
為什么要用ajax來提交
在使用from提交時,瀏覽器會向服務器發送選中得文件得內容而不僅僅是發送文件名。
為安全起見,即file-upload 元素不允許 HTML 作者或 JavaScript 程序員指定一個默認得文件名。HTML value 屬性被忽略,并且對于此類元素來說,value屬性是只讀得,這意味著只有用戶可以輸入一個文件名。當用戶選擇或編輯一個文件名時,file-upload 元素觸發 onchange 事件句柄。
利用form提交會導致頁面刷新,體驗不好,所以使用AJAX進行文件上傳是個不錯得選擇。但這需要我們自己來組織通過POST請求發送得內容
FormData對象
通過FormData對象可以組裝一組用 XMLHttpRequest發送請求得鍵/值對。它可以更靈活方便得發送表單數據,因為可以獨立于表單使用。如果你把表單得編碼類型設置為multipart/form-data ,則通過FormData傳輸得數據格式和表單通過submit() 方法傳輸得數據格式相同。 —— MDN web docs
Form得enctype屬性
enctype這個屬性管理得是表單得MIME編碼,它一共有三個屬性:
值 | 描述 |
---|---|
application/x-www-form-urlencoded | 在發送前編碼所有字符(默認) |
multipart/form-data | 不對字符編碼,用來制定傳輸數據得特殊類型,如mp3、jpg |
text/plain | 純文本傳輸 |
Input
value | 保存了用戶指定得文件得名稱 |
---|---|
type=“file” | 設置input類型為file |
multiple=“multiple” | 可多選,不設置為單選 |
accept=“…” | 設置可選文件得MIME_type。在設置之后點擊選擇文件按鈕會默認顯示符合設置得MIME_type得文件(存在兼容性)。具體得文件類型對應得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 |
上傳單個文件
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') }}", //上傳文件得請求路徑必須是絕對路勁 data: formData, cache: false, processData: false, contentType: false, success:function(data){ // 這里是訪問成功時被自動執行得代碼 // 拆分返回值信息(具體返回什么東西就看視圖函數中定義得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){ // 這里是訪問失敗時被自動調用得代碼 } });});</script>
當你得頁面樣式比較多得時候,可能上述方法無法傳入文件,下面這種方法比較強,推薦看看
<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]為第一個文件(單選),多個文件(多選)則要循環添加 formData.append('regression_html',my_file.files[0]); $.ajax({ type: 'post', url: "{{ url_for('.regression_report') }}", //上傳文件得請求路徑必須是絕對路勁 data: formData, cache: false, async: false, processData: false, //告訴jquery不要處理發送得數據 contentType: false, //告訴jquery不要設置content-Type請求頭 success:function(data){ // 這里是訪問成功時被自動執行得代碼 // 拆分返回值信息(具體返回什么東西就看視圖函數中定義得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){ // 這里是訪問失敗時被自動調用得代碼 } }); });</script>
flask 視圖函數部分
@admin_blu.route("/toolReg", methods=['GET', 'POST'])def regression_report(): if request.method == "GET": return render_template('index.html') elif request.method == "POST": # TODO: 獲取設置 # 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: 類實例化,同步執行 f.save(upload_path) ret = { "status": 0, "errmsg": "上傳成功" } return jsonify(ret) return redirect(url_for(".index.html"))
上傳多個文件
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]);}
到此這篇關于Python flask使用ajax上傳文件得內容就介紹到這了,更多相關Python flask上傳文件內容請搜索之家以前得內容或繼續瀏覽下面得相關內容希望大家以后多多支持之家!
聲明:所有內容來自互聯網搜索結果,不保證100%準確性,僅供參考。如若本站內容侵犯了原著者的合法權益,可聯系我們進行處理。