前端实现请求头中携带参数下载文件

773 阅读1分钟

工作中遇到一个导出文件需求,后端是从请求头中获取token的。使用axios实现往请求头添加token。然后使用a标签download属性。用open with live Sever打开html文件。

html代码:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="./index.css" />
  </head>
  <body>
    <button id="button">下载</button>
  </body>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script src="./1.js"></script>
</html>

js代码:

sessionStorage.setItem('token', '123')
document.getElementById("button").addEventListener("click", function () {
  axios.get('./1.png', {
    responseType: 'blob',
    headers: { 'token': sessionStorage.getItem('token') }
  }).then(res => {
    let a = document.createElement("a");
    a.setAttribute('download', '文件名');
    a.href = window.URL.createObjectURL(res.data);
    document.body.appendChild(a);
    a.click();
    a.remove();
  })
});

image.png 可以看到文件成功下载,并且请求头中有token