JavaScript - 下載檔案 with header access_token

JavaScript - 下載檔案 with header

現在流行前後端分離,

而前端使用vue.js,後端使用Spring Boot

要做下載的處理,或任何請求,都需要header 加入 access_token,

因此要怎麼用javascript做下載呢。而且我要下載的是zip檔,該怎麼處理呢?

我找到一篇文章可以解決這個問題,加以改良就可以變成我需要的方式。

https://nehalist.io/downloading-files-from-post-requests/

改完後如下

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Download GET Request</title>
</head>
<body>
AccessToken
<input type="text" id="access_token" value="test1234">
<select id="testTarget">
  <option value="http://localhost:8080/download">下載測試</option>
</select>

<button id="download">Send AJAX Request and download file</button>

<script>
  document.getElementById('download').addEventListener('click', function () {
    var access_token = document.getElementById('access_token').value;
	var testTarget = document.getElementById('testTarget').value;

    var request = new XMLHttpRequest();
    request.open('GET', testTarget, true);
    request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    request.responseType = 'blob';
	request.setRequestHeader("access_token", access_token);
	
    request.onload = function() {
      // Only handle status code 200
      if(request.status === 200) {
        // Try to find out the filename from the content disposition `filename` value
        var disposition = request.getResponseHeader('content-disposition');
        var matches = /"([^"]*)"/.exec(disposition);
        var filename = (matches != null && matches[1] ? matches[1] : 'file.zip');

        // The actual download
        var blob = new Blob([request.response], { type: 'octet/stream' });
        var link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = filename;

        document.body.appendChild(link);

        link.click();

        document.body.removeChild(link);
      }
      
      // some error handling should be done here...
    };

    request.send('');
  });
</script>
</body>
</html>