最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - remove data:imagepng;base64, from generated base64 string - Stack Overflow

programmeradmin3浏览0评论
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 ?

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 ?

Share Improve this question asked Jul 30, 2021 at 15:39 Andrii RadkevychAndrii Radkevych 3,4527 gold badges35 silver badges65 bronze badges 1
  • 3 What about replacing /data:.*base64,/? – cmolina Commented Jul 30, 2021 at 15:43
Add a ment  | 

2 Answers 2

Reset to default 7

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 ma 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 ma is a required part of the format and is the only piece that separates the data from the rest.

发布评论

评论列表(0)

  1. 暂无评论