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>
where:
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:]
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)
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!