在浏览器中下载arraybuffer文件
export function downloadBuffer(buff, fileName){
let url = window.URL.createObjectURL(new Blob( [buff], {type: "arraybuffer"}) )
const link = document.createElement('a');
link.style.display = 'none';
link.href = url;
link.setAttribute('download', fileName);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
base64转换为流文件
export function dataURLtoBlob(dataUrl) {
let arr = dataUrl.split(',');
let mime = arr[0].match(/:(.*?);/)[1];
let bstr = atob(arr[1]);
let n = bstr.length;
let u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], {
type: mime
});
}
获取文件名后缀
export function getFileExtension(filename) {
const match = filename.match(/\.([^.]+)$/);
return match ? match[1].toLowerCase() : '';
}
下载文件(生成blob)
export function getBlob(url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'blob';
xhr.onload = () => {
if (xhr.status === 200) {
resolve(xhr.response);
} else {
reject(`Request failed with status ${xhr.status}`);
}
};
xhr.onerror = () => {
reject('Request failed');
};
xhr.send();
});
}
Blob 转 Base64
function blobToBase64(blob) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => {
resolve(reader.result);
};
reader.onerror = (err) => reject(err);
reader.readAsDataURL(blob);
});
}
上传文件
export function upload(option) {
const xhr = new XMLHttpRequest();
if (option.onProgress && xhr.upload) {
xhr.upload.onprogress = function progress(e) {
if (e.total > 0) {
e.percent = e.loaded / e.total * 100;
}
option.onProgress(e);
};
}
const formData = new FormData();
formData.append('file', option.file, option.file.name);
if (option.title) {
formData.append('title', option.title);
}
if (option.fileType) {
formData.append('fileType', option.fileType);
}
xhr.onerror = function error(e) {
option.onError(e);
};
xhr.onload = function onload() {
if (xhr.status !== 200) {
return option.onError(JSON.parse(xhr.response));
}
option.onSuccess(JSON.parse(xhr.response));
};
xhr.open('post', option.action, true);
if (option.withCredentials && 'withCredentials' in xhr) {
xhr.withCredentials = true;
}
const headers = option.headers || {};
if (headers['X-Requested-With'] !== null) {
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
}
for (const h in headers) {
if (headers.hasOwnProperty(h) && headers[h] !== null) {
xhr.setRequestHeader(h, headers[h]);
}
}
xhr.send(formData);
return {
abort() {
xhr.abort();
},
};
};