文件url下载
const imgDownload = (url: string, fileName: string) => {
fetch(url).then((response) => response.blob()).then((blob) => {
let blobUrl = window.URL.createObjectURL(blob)
let a = document.createElement('a')
a.href = blobUrl
a.download = fileName
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
})
}
a标签下载
const downloadEvt=(url:string, fileName = '未知文件')=> {
const el = document.createElement('a')
el.style.display = 'none'
el.setAttribute('target', '_blank')
fileName && el.setAttribute('download', fileName)
el.href = url
document.body.appendChild(el)
el.click()
document.body.removeChild(el)
}
form标签下载
const inputDownloadEvt = (
method: string,
url: string,
paramsKey: string,
paramsValue: string
) => {
const form = document.createElement('form')
form.style.display = 'none'
form.setAttribute('target', '_blank')
form.setAttribute('method', method)
form.setAttribute('action', url)
const input = document.createElement('input')
input.setAttribute('type', 'hidden')
input.setAttribute('name', paramsKey)
input.setAttribute('value', paramsValue)
form.appendChild(input)
document.body.appendChild(form)
form.submit()
document.body.removeChild(form)
}
window.open下载
const downloadEvt = (url: string) => {
window.open(url, '_self')
}
iframe下载
const downloadEvt = (url: string) => {
const iframe = document.createElement('iframe');
iframe.style.display = 'none';
iframe.src = url;
document.body.appendChild(iframe);
setTimeout(() => {
document.body.removeChild(iframe);
}, 200);
}
location.href下载
const downloadEvt = (url: string) => {
window.location.href = url;
}
ajax下载(Blob - 利用Blob对象生成Blob URL)
const downloadEvt = (url: string, fileName = '未知文件') => {
const el = document.createElement('a')
el.style.display = 'none'
el.setAttribute('target', '_blank')
fileName && el.setAttribute('download', fileName)
el.href = url
console.log(el)
document.body.appendChild(el)
el.click()
document.body.removeChild(el)
}
const transformRequestData = (contentType: any, requestData: any) => {
requestData = requestData || {}
if (contentType.includes('application/x-www-form-urlencoded')) {
let str = ''
for (const key in requestData) {
if (Object.prototype.hasOwnProperty.call(requestData, key)) {
str += `${key}=${requestData[key]}&`
}
}
return encodeURI(str.slice(0, str.length - 1))
} else if (contentType.includes('multipart/form-data')) {
const formData = new FormData()
for (const key in requestData) {
const files = requestData[key]
const isFile = files
? files.constructor === FileList ||
(files.constructor === Array && files[0].constructor === File)
: false
if (isFile) {
for (let i = 0; i < files.length; i++) {
formData.append(key, files[i])
}
} else {
formData.append(key, files)
}
}
return formData
}
return Object.keys(requestData).length ? JSON.stringify(requestData) : ''
}
const downLoadAjaxEvt = (
method = 'get',
url: string,
params: any,
config: any
) => {
const _method = method.toUpperCase()
const _config = Object.assign(
{
contentType:
_method === 'GET'
? 'application/x-www-form-urlencoded'
: 'application/json',
fileName: '未知文件',
async: true,
token: 'token',
},
config
)
const queryParams = transformRequestData(_config.contentType, params)
const _url = `${url}${
_method === 'GET' && queryParams ? '?' + queryParams : ''
}`
const ajax = new XMLHttpRequest()
ajax.open(_method, _url, _config.async)
ajax.setRequestHeader('Authorization', _config.token)
ajax.setRequestHeader('Content-Type', _config.contentType)
ajax.responseType = 'blob'
ajax.addEventListener('progress', (progress) => {
const percentage = ((progress.loaded / progress.total) * 100).toFixed(2)
const msg = `下载进度 ${percentage}%...`
console.log(msg)
})
ajax.onload = function () {
if (this.status === 200 || this.status === 304) {
const fileReader = new FileReader()
fileReader.onloadend = (e) => {
if (
this.getResponseHeader('content-type')?.includes(
'application/json'
)
) {
const result = JSON.parse(
(fileReader.result as string) ||
'{message: 服务器出现问题,请联系管理员}'
)
alert(result.message)
} else {
const _fileName = decodeURIComponent(
(
this.getResponseHeader('content-disposition') ||
'; filename="未知文件"'
)
.split(';')[1]
.trim()
.slice(9)
)
const blob = new Blob([this.response])
const href = URL.createObjectURL(blob)
downloadEvt(href, _fileName)
URL.revokeObjectURL(href)
}
}
fileReader.readAsText(this.response)
} else {
alert('服务器出现问题,请联系管理员')
}
}
ajax.send(queryParams)
}
ajax下载(Data URL - base64编码后的url)
const downloadEvt=(url:string, fileName = '未知文件')=> {
const el = document.createElement('a')
el.style.display = 'none'
el.setAttribute('target', '_blank')
fileName && el.setAttribute('download', fileName)
el.href = url
console.log(el)
document.body.appendChild(el)
el.click()
document.body.removeChild(el)
}
const transformRequestData=(contentType:string, requestData:any)=> {
requestData = requestData || {}
if (contentType.includes('application/x-www-form-urlencoded')) {
let str = ''
for (const key in requestData) {
if (Object.prototype.hasOwnProperty.call(requestData, key)) {
str += `${key}=${requestData[key]}&`
}
}
return encodeURI(str.slice(0, str.length - 1))
} else if (contentType.includes('multipart/form-data')) {
const formData = new FormData()
for (const key in requestData) {
const files = requestData[key]
const isFile = files
? files.constructor === FileList ||
(files.constructor === Array && files[0].constructor === File)
: false
if (isFile) {
for (let i = 0; i < files.length; i++) {
formData.append(key, files[i])
}
} else {
formData.append(key, files)
}
}
return formData
}
return Object.keys(requestData).length ? JSON.stringify(requestData) : ''
}
const downLoadAjaxEvt=(method = 'get', url:string, params:any, config:any)=> {
const _method = method.toUpperCase()
const _config = Object.assign(
{
contentType:
_method === 'GET'
? 'application/x-www-form-urlencoded'
: 'application/json',
fileName: '未知文件',
async: true,
token: 'token',
},
config
)
const queryParams = transformRequestData(_config.contentType, params)
const _url = `${url}${
_method === 'GET' && queryParams ? '?' + queryParams : ''
}`
const ajax = new XMLHttpRequest()
ajax.open(_method, _url, _config.async)
ajax.setRequestHeader('Authorization', _config.token)
ajax.setRequestHeader('Content-Type', _config.contentType)
ajax.responseType = 'blob'
ajax.addEventListener('progress', (progress) => {
const percentage = ((progress.loaded / progress.total) * 100).toFixed(2)
const msg = `下载进度 ${percentage}%...`
console.log(msg)
})
ajax.onload = function () {
if (this.status === 200 || this.status === 304) {
const fileReader = new FileReader()
fileReader.readAsDataURL(this.response)
fileReader.onload = () => {
if (
this.getResponseHeader('content-type')?.includes(
'application/json'
)
) {
alert('服务器出现问题,请联系管理员')
} else {
const _fileName = decodeURIComponent(
(
this.getResponseHeader('content-disposition') ||
'; filename="未知文件"'
)
.split(';')[1]
.trim()
.slice(9)
)
downloadEvt(fileReader.result, _fileName)
}
}
} else {
alert('服务器出现问题,请联系管理员')
}
}
ajax.send(queryParams)
}
设置各种文件格式的response头中的content-type
| Ext | MIME Type |
|---|
| .doc | application/msword |
| .dot | application/msword |
| .docx | application/vnd.openxmlformats-officedocument.wordprocessingml.document |
| .dotx | application/vnd.openxmlformats-officedocument.wordprocessingml.template |
| .docm | application/vnd.ms-word.document.macroEnabled.12 |
| .dotm | application/vnd.ms-word.template.macroEnabled.12 |
| .xls | application/vnd.ms-excel |
| .xlt | application/vnd.ms-excel |
| .xla | application/vnd.ms-excel |
| .xlsx | application/vnd.openxmlformats-officedocument.spreadsheetml.sheet |
| .xltx | application/vnd.openxmlformats-officedocument.spreadsheetml.template |
| .xlsm | application/vnd.ms-excel.sheet.macroEnabled.12 |
| .xltm | application/vnd.ms-excel.template.macroEnabled.12 |
| .xlam | application/vnd.ms-excel.addin.macroEnabled.12 |
| .xlsb | application/vnd.ms-excel.sheet.binary.macroEnabled.12 |
| .ppt | application/vnd.ms-powerpoint |
| .pot | application/vnd.ms-powerpoint |
| .pps | application/vnd.ms-powerpoint |
| .ppa | application/vnd.ms-powerpoint |
| .pptx | application/vnd.openxmlformats-officedocument.presentationml.presentation |
| .potx | application/vnd.openxmlformats-officedocument.presentationml.template |
| .ppsx | application/vnd.openxmlformats-officedocument.presentationml.slideshow |
| .ppam | application/vnd.ms-powerpoint.addin.macroEnabled.12 |
| .pptm | application/vnd.ms-powerpoint.presentation.macroEnabled.12 |
| .potm | application/vnd.ms-powerpoint.presentation.macroEnabled.12 |
| .ppsm | application/vnd.ms-powerpoint.slideshow.macroEnabled.12 |
| .zip | application/zip |
*注意需要在请求中设置responseType: 'blob'