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

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

Mary-Kate Olsen
Release: 2024-12-01 00:40:11
Original
727 people have browsed it

Why Am I Getting a

Base64 Decoding Error: "Illegal Base64 Data at Input Byte 4"

When attempting to decode a Base64-encoded string using base64.StdEncoding.DecodeString(str), you may encounter the error: "illegal base64 data at input byte 4." This error indicates that the provided input is not in a valid Base64 format.

The issue in your case lies not in the Base64 encoding itself, but in the input string. Instead of a pure Base64 string, you are trying to decode a Data URI scheme.

A Data URI scheme represents data within a web page as inline content, following this format:

data:[][;charset=][;base64],

In your case, the input is a Data URI scheme containing an image/png MIME type and Base64-encoded data. To decode it, you first need to extract the Base64 portion.

input := "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYA"

b64data := input[strings.IndexByte(input, ',')+1:]
fmt.Println(b64data)
Copy after login

Output:

iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYA
Copy after login

Now you can decode the extracted Base64 string:

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

Output:

[137 80 78 71 13 10 26 10 0 0 0 13 73 72 68 82 0 0 0 100 0 0 0 100 8 6 0]
Copy after login

By extracting the Base64 data from the Data URI scheme and performing the decoding process, you can successfully decode the Base64-encoded content.

The above is the detailed content of Why Am I Getting a 'Illegal Base64 Data at Input Byte 4' Error When Decoding a Data URI?. 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