Home > Backend Development > Golang > Why Does `base64.StdEncoding.DecodeString()` Return 'illegal base64 data'?

Why Does `base64.StdEncoding.DecodeString()` Return 'illegal base64 data'?

Susan Sarandon
Release: 2024-12-07 15:12:13
Original
263 people have browsed it

Why Does `base64.StdEncoding.DecodeString()` Return

Illegal Base64 Data in base64.StdEncoding.DecodeString()

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 typically occurs when the input string is not properly Base64 encoded.

Consider the following code:

data, errBase := base64.StdEncoding.DecodeString(Base64Image)
if errBase != nil {
    fmt.Println("error:", errBase)
    return false
}
Copy after login

In this case, the Base64Image variable contains a Base64-encoded string. However, if the input string also contains parts that are not Base64-encoded, such as a Data URI scheme prefix, the decoding process may fail at the first non-Base64 character it encounters.

A Data URI scheme typically starts with "data:" followed by a MIME-type, such as "image/png," and may include a ;base64 string. To extract the actual Base64-encoded data from a Data URI, you need to remove the prefix up to the comma (including the comma).

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

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

Once you have extracted the pure Base64-encoded data, you can then decode it using base64.StdEncoding.DecodeString().

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

By isolating the Base64-encoded data and decoding it correctly, you can avoid the "illegal base64 data" error and successfully process the data as desired.

The above is the detailed content of Why Does `base64.StdEncoding.DecodeString()` Return 'illegal base64 data'?. 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