同種方法-兩種方案:
第一種:頁面上自己手動添加a標簽
第二種:js自動生成a標簽(推薦第二種)
今天在react項目開發過程中,有這樣的一個需求就是文件下載。
自己認為:通過接口請求后端發給返給自己的會是一個文件下載的地址或者路徑什么的,只要把這個地址賦值給a鏈接即可
實際情況:后端發給我的是一端文件流,那么就是需要們自動去解析文件流,然后把解析出來的數據,通過a標簽進行下載
第一種方案:
//點擊文件下載 <div style={styles.downFileBtn} onClick={(event) => { event.preventDefault(); event.stopPropagation(); fetch(downloadFiles, { //downloadFiles 接口請求地址 method: 'get', credentials: 'include', headers: new Headers({ 'Content-Type': 'application/json', 'X-Auth-Token': User.getToken(),//設置header 獲取token }) }).then((response) => { response.blob().then(blob => { let blobUrl = window.URL.createObjectURL(blob); let aElement = document.getElementById('downloadDiv'); //獲取a標簽元素 let filename = times.formatNowDate() + '.zip';//設置文件名稱 aElement.href = blobUrl;//設置a標簽路徑 aElement.download = filename; aElement.click(); window.URL.revokeObjectURL(blobUrl); }); }).catch((error) => { console.log('文件下載失敗', error); }); }} > <Icon type="download"/>文件下載 </div> //定義個a標簽數組 const Anchor = props => { return ( <a {...props}>{props.children}</a> ); }; //頁面上使用a標簽數組 <Anchor id="downloadDiv" style={{display: 'none'}}></Anchor> //隱藏不顯示
第二種方案:(這塊我封裝了一個組件)
/** * @desc:這是一個文件下載組件 * @param:參數說明 * api_url:接口地址 * icon: 下載圖片設置 * text: 下載文本設置 * downFileBtnClass: 按鈕樣式設置 */ import React, {PureComponent} from 'react'; import PropTypes from 'prop-types'; import {Button, Icon} from 'antd'; import User from '/utils/user'; import times from '_TOOLS_/times'; import styles from './index.less'; const downFileBtn = styles.downFileBtn; class FileDown extends PureComponent { constructor(props) { super(props); this.state = { loadingStatus: true, buttonDisabled: false } } //文件下載操作 handleDownFile = (event, api_url) => { event.preventDefault(); event.stopPropagation(); //開啟loading 按鈕置灰 this.setState({ loadingStatus: false, buttonDisabled: true, }); fetch(api_url, { method: 'get', credentials: 'include', headers: new Headers({ 'Content-Type': 'application/json', 'X-Auth-Token': User.getToken(), }), }).then((response) => { response.blob().then(blob => { //關閉loading 按鈕恢復正常 this.setState({ loadingStatus: true, buttonDisabled: false, }); let blobUrl = window.URL.createObjectURL(blob); const filename = times.formatNowDate() + '.zip'; const aElement = document.createElement('a'); document.body.appendChild(aElement); aElement.style.display = 'none'; aElement.href = blobUrl; aElement.download = filename; aElement.click(); document.body.removeChild(aElement); }); }).catch((error) => { //關閉loading 按鈕恢復正常 this.setState({ loadingStatus: false, buttonDisabled: false, }); console.log('文件下載失敗'