Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

格式转化合集 #22

Open
RicoLiu opened this issue Mar 20, 2020 · 0 comments
Open

格式转化合集 #22

RicoLiu opened this issue Mar 20, 2020 · 0 comments

Comments

@RicoLiu
Copy link
Owner

RicoLiu commented Mar 20, 2020

base64转file

/**
*   base64 base64
*   filename 转换后的文件名
*/
base64ToFile = (base64, filename )=> {
  let arr = base64.split(',')
  let mime = arr[0].match(/.*?);/)[1]
  let suffix = mime.split('/')[1] // 图片后缀
  let bstr = atob(arr[1])
  let n = bstr.length
  let u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], `${filename}.${suffix}`, { type: mime })
}

base64转blob

base64ToBlob = base64 => {
  let arr = base64.split(','),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], { type: mime });
};

blob转file

blobToFile = (blob, fileName) => {
  blob.lastModifiedDate = new Date();
  blob.name = fileName;
  return blob;
};

file转base64

/**
 * file 图片文件
 * 返回图片的Base64数据
 */
fileToBase64 = file => {
  let reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = function (e) {
    return e.target.result
  };
}

作者:YXi
链接:https://juejin.im/post/5deb2cdf518825122671b637
来源:掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant