John Doe
John Doe

Reputation: 3243

Is it acceptable to pass a base64 string from the client to the server to utilize?

Is it acceptable to pass a base64 string from the client to the server to save?

Client save I have code that creates a BASE64 string...
data:image/png;base64,iVBORw0KGgoAAAANSUh.....etc....

However when I try to convert this server side I get an error that input is not a valid Base-64 string.

In my C# code I have:

// Data Type
public List<object[][]> MyData;


var imgStr = MyData[0][0].ToString();
var bytes = Convert.FromBase64String(imgStr); // Get error here

Is there a better way to take an image from client slide and pass it server side to use?

Upvotes: 1

Views: 1259

Answers (3)

anucreative
anucreative

Reputation: 98

Following @benstopics response, it might be easier to strip the metadata by splitting on the comma and then taking the second part e.g.

String base64 = "data:image/png;base64,iVBORw0KGgoAAAANSUh.....";
base64 = base64.split(',')[1];

Upvotes: 1

benstopics
benstopics

Reputation: 124

Base64 is made up of characters A-Z, a-z, 0-9, +, and /, putting aside the number of = characters that must be placed at the end (the most complicated part about Base64 *encoding),

As you can see in your data string, the data:image/png;base64, prefix is simply metadata and is not part of any valid Base64 encoded string. Here is a way you could remove this from your string:

String base64 = "data:image/png;base64,iVBORw0KGgoAAAANSUh.....";
base64 = base64.substring(22, base64.length());

If you want it to work for any image type, you will need to use a regular expression.

Upvotes: 1

driis
driis

Reputation: 164331

You need to strip the data:image/png;base64, from the string. That's metadata. The actual base64 encoded bytes begins after the comma.

Upvotes: 4

Related Questions