前端数据流文件下载三种方式 | 蛋烘糕
蛋烘糕.

不写博客的工程师不是好的搬砖工🧱

前端数据流文件下载三种方式

Cover Image for 前端数据流文件下载三种方式
蛋烘糕
蛋烘糕

1、直接使用 get 请求方式进行下载:

window.open(`${url}?${qs.stringify(param)}`, "_blank");

2、使用 form 表单 post 请求进行下载:

const postDownloadFile = (action, param) => {
  const form = document.createElement("form");
  form.action = action;
  form.method = "post";
  form.target = "blank";
  Object.keys(param).forEach((item) => {
    const input = document.createElement("input");
    input.type = "hidden";
    input.name = item;
    input.value = param[item];
    form.appendChild(input);
  });
  document.body.appendChild(form);
  form.submit();
  document.body.removeChild(form);
};

postDownloadFile(url, param);

3、axios(ajax)前端根据返回数据流生成文件下载:

axios
  .post(url, param, {
    responseType: "blob",
  })
  .then((res) => {
    console.log("res", res);
    const blob = res.data;
    const reader = new FileReader();
    reader.readAsDataURL(blob);
    reader.onload = (e) => {
      const a = document.createElement("a");
      a.download = `文件名称.zip`;
      // 后端设置的文件名称在res.headers的 "content-disposition": "form-data; name=\"attachment\"; filename=\"odps_ddl_20181211191944.zip\"",
      a.href = e.target.result;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    };
  })
  .catch((err) => {
    console.log(err.message);
  });
一些常用的正则表达式
JavaScript this 对象查找
博客日历
2022年10月
26
27
28
29
30
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
01
02
03
04
05
06
更多