Home > Backend Development > Golang > Why Am I Getting an 'Illegal Base64 Data at Input Byte 4' Error When Decoding a Base64 String?

Why Am I Getting an 'Illegal Base64 Data at Input Byte 4' Error When Decoding a Base64 String?

Mary-Kate Olsen
Release: 2024-11-29 16:24:10
Original
639 people have browsed it

Why Am I Getting an

Exception: Illegal Base64 Data at Input Byte 4

When attempting to decode a base64-encoded string using base64.StdEncoding.DecodeString, an "illegal base64 data at input byte 4" error may occur. This error stems from the improper handling of Data URI schemes.

Data URI schemes encode data inline within web pages, resembling external resources. Their format resembles:

data:[<MIME-type>][;charset=<encoding>][;base64],<data>
Copy after login

where:

  • specifies the data's type (e.g., image/png)
  • indicates the character encoding (optional)
  • ";base64" signifies Base64 encoding
  • contains the actual data encoded in Base64

To rectify the issue in your scenario, you must extract the base64-encoded data from the Data URI scheme before decoding. To achieve this, remove the prefix up to the comma:

input := "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYA"
b64data := input[strings.IndexByte(input, ',') + 1:]
Copy after login

Now you have the base64-encoded data, which can be decoded successfully:

data, err := base64.StdEncoding.DecodeString(b64data)
if err != nil {
    fmt.Println("error:", err)
}
fmt.Println(data)
Copy after login

The above is the detailed content of Why Am I Getting an 'Illegal Base64 Data at Input Byte 4' Error When Decoding a Base64 String?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template