Java教程

Base64编码图片信息转换为File上传

本文主要是介绍Base64编码图片信息转换为File上传,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

工作中,我们经常需要把Base64编码图片上传到服务器或七牛云,

格式如下:

data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCAJIBAwDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMi

  先把上面base64字符串转换为Blob

function dataURLtoBlob(dataURI:string) {
    let byteString = atob(dataURI.split(',')[1]);
    let mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
    let ab = new ArrayBuffer(byteString.length);
    let ia = new Uint8Array(ab);
    for (let i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }
    return new Blob([ab], { type: mimeString });
  
}

Blob转换为File

let blob: any = fileutil.dataURItoBlob(imageData);

 let file = new File([blob], "file" + id, {
    type: blob.type,
    lastModified: Date.now(),
  });

组成FormData

  let form = new FormData();
  form.append("id", “1“);
  form.append("name", "小花猫”);
   form.append("image_file", file);

//...调用web接口上传

 

这篇关于Base64编码图片信息转换为File上传的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!