导出文件
export function downloadFileByBlob(file, fileName) {
const fileBlob = new Blob([file]);
const objUrl = URL.createObjectURL(fileBlob);
const a = document.createElement("a");
a.style.display = "none";
a.href = objUrl;
a.download = fileName;
a.click();
URL.revokeObjectURL(objUrl)
}
export function downloadFile(url, fileName='Log.xlsx', config) {
return request({
url: url,
method: 'get',
responseType: 'blob',
...config
})
.then(blob => {
const ele = document.createElement('a')
const objUrl = URL.createObjectURL(blob);
ele.href = objUrl;
ele.download = fileName;
ele.click()
URL.revokeObjectURL(objUrl)
})
}
export function downloadFileByUrl(path, fileName) {
if(!path) {
throw "File path is required"
}
const arr = path.split('/')
const defaultName = arr[arr.length - 1].split('?')[0]
const ele = document.createElement('a')
ele.setAttribute('href', path)
ele.setAttribute('target', `_blank`)
ele.setAttribute('download', fileName || defaultName)
ele.click()
}
export function downloadImgByBlob(url, name) {
var img = new Image()
img.onload = function() {
var canvas = document.createElement('canvas')
canvas.width = img.width
canvas.height = img.height
var ctx = canvas.getContext('2d')
ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
let type = 'image/png'
if(name){
const typeObj = {
'png': 'image/png',
'jpg': 'image/jpeg'
}
let arr = name.split('.')
type = typeObj[arr[arr.length - 1]]
}
canvas.toBlob((blob) => {
var blobUrl = window.URL.createObjectURL(blob)
var a = document.createElement('a')
a.href = blobUrl
a.download = name || ''
a.click()
}, type)
}
img.src = url
img.setAttribute('crossOrigin', 'Anonymous')
}
export function uploadFile(file, url, fileKey, config) {
fileKey = fileKey || 'file'
const formData = new FormData()
if (file instanceof Array) {
for (const key in file) {
formData.append(fileKey, file[key])
}
} else {
formData.append(fileKey, file)
}
return request({
url: url,
method: 'post',
data: formData
})
}
export function downloadFileUrlToBlob(url, fileName) {
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'blob';
xhr.onload = function() {
if (xhr.status === 200) {
downloadFileByBlob(xhr.response, fileName)
}
};
xhr.send();
}
export const downloadBuffer = ({name=Date.now(), code, type}) => {
const b = new Blob(code, type && type)
var a=document.createElement("a");
a.href=URL.createObjectURL(b)
a.download=`${name}`;
a.click();
URL.revokeObjectURL(b);
}
export function encode(str) {
let base64 = btoa(str)
return base64
}
export function decode(base64) {
let str = atob(base64)
return str
}
export function file2Base64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader()
reader.readAsDataURL(file)
reader.onload = () => resolve(reader.result)
reader.onerror = (error) => reject(error)
})
}