post方式實現導出/下載文件


項目需求: 前端需要傳入過多的參數給后端,get地址欄不行,只能接受post方式去導出數據

1、get的下載方式

通常下載方式如下:
 let url =  xxxx.action?a=xx&b=yy;
 window.location.href = url;
 // 或者
 window.open(url, '_self')

弊端:當請求參數較多時,get的方式無法使用,這時候需要考慮post的方式,但是直接通過ajax的post的方式無法調用瀏覽器的下載功能

2、post的下載方式

原理: 創建一個隱藏form表單,通過form表單的提交刷新功能,實現下載。代碼如下:

    // vue項目代碼
  // 導出excel
    postExcelFile(params, url) {
      //params是post請求需要的參數,url是請求url地址
      var form = document.createElement("form");
      form.style.display = "none";
      form.action = url;
      form.method = "post";
      document.body.appendChild(form);
    // 動態創建input並給value賦值
      for (var key in params) {
        var input = document.createElement("input");
        input.type = "hidden";
        input.name = key;
        input.value = params[key];
        form.appendChild(input);
      }

      form.submit();
      form.remove();
    }

    //調用
     this.postExcelFile(
        { currentPage: 2, pageSize: 20 },
        'url/xxxxxxx/'
      );

注意點:傳給后端的參數不是json對象的形式,而是 currentPage=2&pageSize=20, 因此需要后端兄弟的配合

更多內容來源本人博客: https://shengchangwei.github.io/vue-post-down/

 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM