日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

下載文件時前端重命名的實現方法將url地址轉化為文件實現重命名

作者:小小清233 更新時間: 2023-10-18 編程語言

最近在項目中遇到一個需求,用戶可以點擊按鈕下載文件,后端返回給前端的是文件的絕對地址。
最開始我是用的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

  • 上一篇:沒有了
  • 下一篇:沒有了
欄目分類
最近更新