Girish K G
Girish K G

Reputation: 417

Read base64 data from InputStream to file C#

my application gets image from clipboard and saves it to server. getting image is done through java and javascript. my aspx codebehind receives this data (base64) and writes to file. here is my code

  byte[] buffer = new byte[Request.InputStream.Length];
    int offset = 0;
    int cnt = 0;
    while ((cnt = Request.InputStream.Read(buffer, offset, 10)) > 0)
    {
        offset += cnt;
    }
    fileName = DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".png";
    string base64 = System.Text.Encoding.UTF8.GetString(buffer);

    byte[] bytes = Convert.FromBase64String(base64);
    System.IO.FileStream stream = new FileStream(@"D:\www\images\" + fileName, FileMode.CreateNew);
    System.IO.BinaryWriter writer =new BinaryWriter(stream);
    writer.Write(bytes, 0, bytes.Length);
    writer.Close(); 

my problem is base64 . i get this string as utf8 encoded. seems this tampers the image and i am not able to open or view them.

[EDIT] Here is the java code that creates the data

StringBuffer sb = new StringBuffer();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
sb.append("data:image/").append("png").append(";base64,").append(Base64.encode(stream.toByteArray()));

so i will get a string like this data:image/png;base64,iVBORw0KGgoA.. and using ajax i posts this string to my aspx page

Upvotes: 2

Views: 12650

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039428

You should remove the data:image/png;base64, prefix when you read the input stream before base64 decoding. For example you could split at the ,:

byte[] buffer = new byte[Request.InputStream.Length];
Request.InputStream.Read(buffer, 0, buffer.Length);
string data = Encoding.Default.GetString(buffer);
string[] tokens = data.Split(',');
if (tokens.Length > 1)
{
    byte[] image = Convert.FromBase64String(tokens[1]);
    string fileName = DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".png";
    string path = Path.Combine(@"D:\www\images", fileName);
    File.WriteAllBytes(path, image);
}

Upvotes: 5

Related Questions