大家好!我叫戴向天
QQ群:602504799
/**
* Author: 戴向天
* 文件下载
* 使用方法
* const server = new DownloadServer({
* baseUrl: ''
* })
* server.run('get', url).then(res => {
* downloadByURL(res.url, fileName) // 直接下载
* })
* @return {Promise}
*/
export default class downloadServer {
constructor (config) {
this.baseUrl = config.baseUrl || ''
this.headers = config.headers || {}
return this
}
run (type, url, params, headers = {}, onprogress) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.responseType = 'blob'
xhr.open(type, this.baseUrl + url, true)
headers = {
...this.headers,
...headers
}
for (const key in headers) {
xhr.setRequestHeader(key, headers[key])
}
xhr.onreadystatechange = () => {
if (xhr.readyState === 4 && xhr.status === 200) {
const resultType = xhr.response.type
if (resultType === 'application/json') {
var reader = new FileReader()
reader.onload = function (event) {
var content = reader.result
resolve(JSON.parse(content))
}
return reader.readAsText(xhr.response)
}
const response = xhr.getAllResponseHeaders().trim().split(/[\r\n]+/)
const headerMap = {}
response.forEach(function (line) {
const parts = line.split(': ')
const header = parts.shift()
const value = parts.join(': ')
headerMap[header] = value
})
const fileName = decodeURI(headerMap['content-disposition']).split('=').pop()
const fileType = fileName.split('.')[1]
let type // 产生二进制blob的MIME类型
switch (fileType) {
case 'xls' || 'xlsx':
// 为excel文件
type = 'application/vnd.ms-excel'
break
case 'doc':
type = 'application/msword'
break
case 'docx':
type =
'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
break
case 'pdf':
type = 'application/pdf'
break
case 'bmp':
type = 'image/bmp'
break
case 'png':
type = 'image/png'
break
case 'gif':
type = 'image/gif'
break
case 'jpe' || 'jpeg' || 'jpg':
type = 'image/jpeg'
break
}
const blobStream = new Blob([xhr.response], { type })
const url = window.URL.createObjectURL(blobStream)
resolve({ url, fileName })
}
}
if (onprogress) {
xhr.onprogress = onprogress
}
xhr.onerror = (event) => {
reject(event)
}
const isForm = Object.prototype.toString.call(params).toLowerCase().indexOf('formdata') >= 0
xhr.send(isForm ? params : typeof params === 'string' ? params : JSON.stringify(params))
})
}
}