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);
  },
相关文章
相关标签/搜索