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 }
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)
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)
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!