js-post方式下載文件

/*
   *@functionName: postDownload
   *@params: config  對象 {url:請求路徑,data:請求參數}
   *@description:post請求下載文件
   *@date: 2020-08-24 13:47:07
   */
  postDownload(config) {
    // 建立iframe
    var iframe = document.createElement("iframe");
    iframe.setAttribute("id", "downFilePostIframe");
    iframe.setAttribute("name", "downFilePostIframe");
    iframe.setAttribute("enctype", "multipart/form-data");
    iframe.style.height = "0px";
    iframe.style.display = "none";
    // 建立form
    const form = document.createElement("form");
    form.setAttribute("target", "down-file-iframe");
    form.setAttribute("method", "post");
    form.setAttribute("id", "downFilePostForm");
    form.setAttribute("action", config.url);
    // 組裝表單數據
    Object.keys(config.data).forEach((key) => {
      const input = document.createElement("input");
      input.setAttribute("type", "hidden");
      input.setAttribute("name", key);
      input.setAttribute("value", config.data[key]);
      form.appendChild(input);
    });

    document.body.appendChild(iframe);
    document.body.appendChild(form);
    // 提交
    form.submit();
    // 刪除iframe和表單
    document.body.removeChild(iframe);
    document.body.removeChild(form);
  },
相關文章
相關標籤/搜索