react實現下載文件


   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);
        });
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM