react實現下載檔案
阿新 • • 發佈:2021-08-12
downloadFile=(filePath, filename)=>{ axios.post(filePath, '', { headers: { 'Content-Type': 'application/x-www-form-urlencoded', //請求的資料型別為form data格式 }, 'responseType': 'blob' //設定響應的資料型別為一個包含二進位制資料的 Blob 物件,必須設定!!! }).then(function(response) { const blob = new Blob([response.data]); const fileName = filename; const linkNode = document.createElement('a'); linkNode.download = fileName; //a標籤的download屬性規定下載檔案的名稱 linkNode.style.display = 'none'; linkNode.href= URL.createObjectURL(blob); //生成一個Blob URL document.body.appendChild(linkNode); linkNode.click(); //模擬在按鈕上的一次滑鼠單擊 URL.revokeObjectURL(linkNode.href); // 釋放URL 物件 document.body.removeChild(linkNode); }).catch(function (error) { console.log(error); }); }