简体   繁体   中英

remove data:image/png;base64, from generated base64 string

export const convertFileToBase64 = file => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()

    reader.readAsDataURL(file)

    reader.onload = () => {
      if (reader.result) {
        resolve(reader.result)
      } else {
        reject(Error('Failed converting to base64'))
      }
    }
  })
}

What i wan't is to understand is it possible to generate base 64 without addition data:image/png;base64, at the beginning of the string, maybe someone say user string replace method , and remove it , but I also wait on png file, pdf file , etc. Is it possible to improve my method and remove it ?

If I've understood correctly you can achieve your goal using regex and replace() like this.

 const str1 = "data:image/png;base64,moredatablablabla" const str2 = "data:application/pdf;base64,datadatadatablabla" const regex = /data:.*base64,/ console.log(str1.replace(regex,"")) console.log(str2.replace(regex,""))

Just split the string on the comma and get the part after.

const getDataPart = (dataUrl) => dataUrl.split(',', 1)[1];

console.log(getDataPart('data:image/png;base64,somebase64stuff'));

Coincidentally, this works on any data url encoding as a comma is a required part of the format and is the only piece that separates the data from the rest.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM