日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

Python?flask使用ajax上傳文件的示例代碼_python

作者:CDamogu ? 更新時(shí)間: 2022-09-20 編程語言

前言

JS

為什么要用ajax來提交
在使用from提交時(shí),瀏覽器會(huì)向服務(wù)器發(fā)送選中的文件的內(nèi)容而不僅僅是發(fā)送文件名。

為安全起見,即file-upload 元素不允許 HTML 作者或 JavaScript 程序員指定一個(gè)默認(rèn)的文件名。HTML value 屬性被忽略,并且對于此類元素來說,value屬性是只讀的,這意味著只有用戶可以輸入一個(gè)文件名。當(dāng)用戶選擇或編輯一個(gè)文件名時(shí),file-upload 元素觸發(fā) onchange 事件句柄。

利用form提交會(huì)導(dǎo)致頁面刷新,體驗(yàn)不好,所以使用AJAX進(jìn)行文件上傳是個(gè)不錯(cuò)的選擇。但這需要我們自己來組織通過POST請求發(fā)送的內(nèi)容
FormData對象

通過FormData對象可以組裝一組用 XMLHttpRequest發(fā)送請求的鍵/值對。它可以更靈活方便的發(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 不對字符編碼,用來制定傳輸數(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的文件(存在兼容性)。具體的文件類型對應(yīng)的MIME類型可以搜索到,這里列出我用到的類型:

MIME類型(更多直接百度,類型超乎你的想想)

文件類型 MIME類型
.txt text/plain
.pdf 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') }}", //上傳文件的請求路徑必須是絕對路勁
    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') }}", //上傳文件的請求路徑必須是絕對路勁
            data: formData,
            cache: false,
            async: false,
            processData: false, //告訴jquery不要處理發(fā)送的數(shù)據(jù)
            contentType: false, //告訴jquery不要設(shè)置content-Type請求頭
            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]);
}

原文鏈接:https://blog.csdn.net/qq_33704787/article/details/126003341

欄目分類
最近更新