下载文件时前端重命名的实现方法将url地址转化为文件实现重命名

最近在项目中遇到一个需求,用户可以点击按钮下载文件,后端返回给前端的是文件的绝对地址。
最开始我是用的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是文件的名字,要加上文件的拓展名
}
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值