Upload your avatar as an example

Convert base64 to file

Click the profile picture and select the file

When you click select, you get the base64 file

Vue-imgcut is used here

Code parsing

function base64toFile(dataurl, filename = "file") {
      let arr = dataurl.split(",")
}
Copy the code

The console. The log (arr) 👇

let mime = arr[0].match(/:(.*?) ; / [1]);Copy the code

The console. The log (mime) 👇

console.log(arr[0].match(/:(.*?) ; 👇 /))

let suffix = mime.split("/")[1];
let bstr = atob(arr[1]);
Copy the code

The console. The log (BSTR) 👇

let n = bstr.length;
let u8arr = new Uint8Array(n);
Copy the code

The console. The log (n) 👇

The console. The log (u8arr) 👇

while (n--) {
  u8arr[n] = bstr.charCodeAt(n)
}
Copy the code

The console. The log (BSTR. CharCodeAt (n)) 👇

The console. The log 👇 ([u8arr])

return new File([u8arr], `${filename}.${suffix}`, {
  type: mime
})
Copy the code

The complete code is as follows

function base64toFile(dataurl, filename = "file") { let arr = dataurl.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 }); }Copy the code

When a POST request is sent to the server: