axios使用get请求下载资源

问题

下载类似这种非静态文件资源地址时, 需要将axios默认的响应类型进行修改, 在获取到数据后写入文件

https://xxx.xxx/download

解决

let resUrl: string = "https://xxx.xxx/download"
axios.create({
      timeout: 3000,
      responseType: "blob", // 响应类型, 将响应数据转换为二进制数据
      headers: {},
    })
    .get(resUrl)
    .then((res: any) => {
      console.log(res);
      // 地址转换
      let url = window.URL.createObjectURL(res.data);
      // 文件名
      let fileName: string = "fileName.xxx";
      const a = document.createElement("a");
  	  a.setAttribute("href", url);
      a.setAttribute("download", fileName);
      document.body.append(a);
      a.click();
      document.body.removeChild(a);
    });
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐