常用的处理文件的方法


在浏览器中下载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

/**
 * Blob 转 Base64
 * @param {Blob} blob 二进制文件
 * @returns {Promise<string>} base64 字符串
 */
function blobToBase64(blob) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => {
      // reader.result 就是完整 base64(含 data:application/pdf;base64, 前缀)
      resolve(reader.result);
    };
    reader.onerror = (err) => reject(err);
    // 读取为 Base64 DataURL
    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();
		},
	};
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值