KyLim KyLim - 18 days ago 12
C# Question

c# Convert base64 to jpg image

protected void ExportToImage(object sender, EventArgs e)
{
string base64 = Request.Form[hfImageData.UniqueID].Split(',')[1];
byte[] bytes = Convert.FromBase64String(base64);
File.Copy(bytes.ToString()+".jpg", "\\\\192.168.2.9\\Web");
}


hfImageData data i get from jquery,after user do the drawings,i will convert the convas into base64 .
then will call c# function to convert from base64 to jpg image file into server and store into DB.

when i trigger the onclick button im getting error :System.IO.FileNotFoundException: Could not find file 'System.Byte[].jpg'.

any ideas why?

Answer

In this line File.Copy(bytes.ToString()+".jpg", "\\\\192.168.2.9\\Web"); you are effectively trying to convert content of the bytes array and use it as an image name, but this will not actually create the file.

bytes.ToString() simply returns the type of the object not the content. That's why you are seeing System.Byte[].jpg

The way to solve the issue is to change your function:

protected void ExportToImage(object sender, EventArgs e)
{
    string base64 = Request.Form[hfImageData.UniqueID].Split(',')[1];
    byte[] bytes = Convert.FromBase64String(base64);
    //write the bytes to file:
    File.WriteAllBytes(@"c:\temp\somefile.jpg", bytes); //write to a temp location.
    File.Copy(@"c:\temp\somefile.jpg", @"\\192.168.2.9\Web");//here we grab the file and copy it.
    //EDIT: based on permissions you might be able to write directly to the share instead of a temp folder first.
}
Comments