一:我们的需求是下载txt,但是常规的方法都是直接打开了txt
这样是直接打开了
window.open('https://xxxxx.txt')
二:下载txt方法
- utils里面创建以下js
export const downloadFile = (url, name) => {
window.fetch(url)
.then(res => {
if (res.status === 200) {
return res.blob()
}
return false
}, (error) => {
console.log(error)
})
.then(
blob => {
const a = document.createElement('a')
document.body.appendChild(a)
a.style.display = 'none'
// 使用获取到的blob对象创建的url
const url = window.URL.createObjectURL(blob)
a.href = url
// 指定下载的文件名
a.download = `${name}`
a.click()
document.body.removeChild(a)
// 移除blob对象的url
window.URL.revokeObjectURL(url)
},
)
}
二:导入
- 导入
import { downloadFile } from '@/utils/download.js'
三:使用
- 使用
/** @function 下载模板 */
downloadTemp() {
downloadFile('https://xxxxx.txt', '文件名字.txt')
}