fetch下载文件

let fileName = '';
      let options = {
        method: "POST", //post请求
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json",
          "X-Token": getToken(),
        },
        body: JSON.stringify({
          type: "exercises",
        }),
      };
      fetch(`${VUE_APP_BASE_API}/teachingresource/question/export `, options)

          .then((res) => {
            // 切割出文件名
            const fileNameEncode = res.headers.get('content-disposition').split('filename=')[1]
            // 解码
            fileName = decodeURIComponent(fileNameEncode)
            console.log('fileName', fileName)

            return res.blob();
          })
          .then((blob) => {

            const a = document.createElement("a");
            document.body.appendChild(a);
            a.style.display = "none";
            const url = window.URL.createObjectURL(blob);
            a.href = url;
            a.download = fileName;
            a.click();
            document.body.removeChild(a);
            window.URL.revokeObjectURL(url);
          });
posted @ 2022-12-28 15:36  士广  阅读(322)  评论(0)    收藏  举报