.net做的學(xué)校網(wǎng)站百度下載安裝免費(fèi)
文章目錄
- 上傳
- 下載
- 進(jìn)度條
場(chǎng)景:要上傳一個(gè)zip,調(diào)用接口,然后下載一個(gè)zip。調(diào)用接口的接口響應(yīng)要顯示在進(jìn)度條中。
上傳
上傳用的是input原生控件,在頁(yè)面中隱藏。accept="application/zip"
限制只能上傳zip。
點(diǎn)擊button實(shí)現(xiàn)上傳,調(diào)用input原生組件的方法。
<el-buttontype="primary"size="large"@click="uploadSrt">上傳srt</el-button
>
<inputref="srtInput"type="file"style="display: none"accept="application/zip"@change="handleUploadSrt"/>
在event中拿到上傳的文件file。
注意,要使用formData和'Content-Type': 'multipart/form-data'
,以支持二進(jìn)制的傳輸。
不能用application/json
的響應(yīng)頭,File對(duì)象不能被序列化為JSON。
詳情看注釋。
uploadSrt() {this.$refs.srtInput.click()
},
// input原生控件的上傳事件,file是拿到的文件
handleUploadSrt(event) {const file = event.target.files[0]this.upload(file)
},upload(file) {// 用FormData,支持二進(jìn)制數(shù)據(jù)傳輸let formData = new FormData()formData.append('file', file)axios.post('url', formData, {headers: {'Content-Type': 'multipart/form-data',},// 進(jìn)度條進(jìn)度onDownloadProgress: (progressEvent) => {if (progressEvent.total > 0) {this.srtProgress = Math.round((progressEvent.loaded * 100) / progressEvent.total)} else {this.srtProgress = 100 // 防止progressEvent.total為0出現(xiàn)無(wú)限大}},timeout: 10000, // 設(shè)置超時(shí)時(shí)間,若接口在10s內(nèi)沒(méi)響應(yīng)就拋出異常,在catch中捕獲}).then((response) => {// 響應(yīng)后的邏輯}).catch((error) => {// 異常的邏輯})
},
下載
請(qǐng)求某個(gè)接口下載文件。
請(qǐng)求要設(shè)置參數(shù),表示是二進(jìn)制文件:responseType: 'blob'
。
創(chuàng)建一個(gè)url和a標(biāo)簽,點(diǎn)擊a標(biāo)簽則下載。
download(type) {let url = 'url'axios.get(url, { responseType: 'blob', timeout: 10000 }).then((res) => {const fileName='' // 設(shè)置下載的文件名// 創(chuàng)建一個(gè)下載url和a標(biāo)簽const downloadUrl = window.URL.createObjectURL(new Blob([res.data])) // res.data 是要下載的文件const link = document.createElement('a')link.href = downloadUrl// 設(shè)置download屬性,點(diǎn)擊鏈接就能下載link.setAttribute('download', `${fileName}`)// 將a標(biāo)簽加在文檔中,點(diǎn)擊下載document.body.appendChild(link)link.click() }).catch((error) => {// ...})},
進(jìn)度條
用ElementPlus的組件el-progress
,傳入一個(gè)srtProgress即可。不過(guò)效果是一下就閃到100了(可能是接口響應(yīng)很快??)。
<el-progress:percentage="srtProgress"status="warning":stroke-width="12"
/>
最后改為,不要設(shè)置超時(shí)。給接口多一點(diǎn)時(shí)間,有道理!