網站首頁 編程語言 正文
最近在項目中遇到一個需求,用戶可以點擊按鈕下載文件,后端返回給前端的是文件的絕對地址。
最開始我是用的windown.open()
實現,但是使用這個方法下載的文件名是亂碼,測試要求將文件名固定。通過查閱資料,我了解到可以將url地址轉為blob文件對象從而實現對文件的重命名,代碼如下:
// 將文件路徑轉為blob
function getBlob (url) {
return new Promise(resolve => {
const xhr = new XMLHttpRequest()
// 避免 200 from disk cache
xhr.open('GET', url, true)
xhr.responseType = 'blob'
xhr.onload = () => {
if (xhr.status === 200) {
resolve(xhr.response)
}
}
xhr.send()
})
}
function saveAs (blob, filename) {
if (window.navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(blob, filename)
} else {
const anchor = document.createElement('a')
const body = document.querySelector('body')
anchor.href = window.URL.createObjectURL(blob)
anchor.download = filename
anchor.style.display = 'none'
body.appendChild(anchor)
anchor.click()
body.removeChild(anchor)
window.URL.revokeObjectURL(anchor.href)
}
}
export async function download (url, newFileName) {
const blob = await getBlob(url)
saveAs(blob, newFileName)
//newFileName是文件的名字,要加上文件的拓展名
}
原文鏈接:https://blog.csdn.net/weixin_42116120/article/details/124243275
- 上一篇:沒有了
- 下一篇:沒有了
相關推薦
- 2022-09-09 C語言中回調函數和qsort函數的用法詳解_C 語言
- 2022-03-24 postman接口做關聯測試的方法步驟_相關技巧
- 2023-12-06 Warn: Could not find @TableId
- 2022-07-16 (ES6以上以及TS) Map對象轉數組
- 2023-01-15 React?Fiber樹的構建和替換過程講解_React
- 2022-04-28 Python可視化學習之seaborn繪制矩陣圖詳解_python
- 2022-07-06 C++使用easyx實現打磚塊游戲_C 語言
- 2022-11-24 Python?Django中間件詳細介紹_python
- 欄目分類
-
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支