Ciel
Ciel

Reputation: 4440

cannot succeed in using Convert.FromBase64String on... base64string in C#/.NET Core

I am using Cropper to crop an image in a web application, and then send the result as a base64 string to my ASP.NET Core controller. So far, I've not figured out the data type necessary to send it correctly, but in the meantime dynamic or a custom data type works;

I crop the image, and then try to send it in;

var base64string = cropperWidgetInstance.getCroppedCanvas().toDataUrl('image/jpeg');
$http.post('url', { data: base64string });

in my ASP.NET Controller, I'm receiving the data like this;

public async Task<IActionResult> SaveCroppedImage([FromBody] dynamic data) {

}

this gives me an object called data, with a property itself called data that contains a string like this;

data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgICAgMCAgIDAwMDBAYEBAQEBAgGBgUGCQgKCgkICQkKDA8MCgsOCwkJDRENDg8QEBEQCgwSExIQEw8QEBD/2wBDAQMDAwQDBAgEBAgQCwkLEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBD/wAARCAGTAswD ....

This looks like it should work fine, but when I try to use

Convert.FromBase64String(data.data)

It gives me the exception

icrosoft.CSharp.RuntimeBinder.RuntimeBinderException: The best overloaded method match for 'System.Convert.FromBase64String(string)' has some invalid arguments

I really have no idea what is going wrong here. I can't find any article on the topic that doesn't follow the exact same steps of just using Convert.FromBase64String.

Upvotes: 1

Views: 1982

Answers (1)

Hetal Rupareliya
Hetal Rupareliya

Reputation: 387

you have data in form of :

data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgICAgMCAgIDAwM
DBAYEBAQEBAgGBgUGCQgKCgkICQkKDA8MCgsOCwkJDRENDg8QEBEQCgwSExIQEw8QEBD/2wBDA
QMDAwQDBAgEBAgQCwkLEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBA
QEBAQEBAQEBD/wAARCAGTAswD ....

if you want to convert it in FromBase64String then you have to remove "data:image/jpeg;base64," from your string and then convert it to FromBase64String

you can replace it like below code

string strdata = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMC.... 

var strstring = strdata.replace("data:image/jpeg;base64,", '');

and then try to convert it

Convert.FromBase64String(strstring);

it works for me try this..

Upvotes: 2

Related Questions