import axios from './axios'
export const requestBaseUpload = (url, params, type = 'post', headers = { 'Content-Type': 'multipart/form-data' }, options = {}, loading = true) => {
const data = new FormData()
const keys = Object.keys(params)
keys.forEach(key => data.append(key, params[key]))
options.headers = Object.assign(headers, options.headers)
return axios[type](url, data, options, loading)
}
/**
* 谷歌 火狐 IE10+
* 小版本或者老版本没有测试
*/
export const requestBaseDownload = (url, params, fileName = '', type = 'get', options = { responseType: 'blob' }, loading = true) => {
return axios[type](url, params, options, loading).then(data => {
if (!data || !data.data) {
return
}
// 根据请求获取文件名
if (!fileName) {
const re = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/i
const disposition = data.headers['content-disposition']
const match = disposition && disposition.match(re)
if (match) {
fileName = match[1]
}
}
if (navigator.msSaveBlob) {
// 兼容 IE
navigator.msSaveBlob(new Blob([data]), fileName)
return
}
// 使用 a[download] 方式下载
const url = window.URL.createObjectURL(new Blob([data.data]))
const link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('download', fileName)
document.body.appendChild(link)
// 兼容不支持 link.click()
const evt = new MouseEvent('click')
link.dispatchEvent(evt)
// 兼容不支持 link.remove()
document.body.removeChild(link)
})
}
// 断点上传,数据处理
// cb 用来接收处理好的分片数据
export const requestBaseSpliceUpload = (file, size = 1024 * 1024, cb = () => {}) => {
var reader = new FileReader()
reader.readAsArrayBuffer(file)
reader.addEventListener('load', () => {
const data = []
const [name, ext] = file.name.split('.')
for (let i = 0, len = this.result.byteLength; i < len; i += size) {
data.push(this.result.slice(i, i + size))
}
cb({ name, ext, data })
})
}
文件下载、上传和断点续传数据处理的公共基本方法
最新推荐文章于 2024-02-26 09:47:32 发布