0

I am converting an image to byte array on client side in my wp7 app and then sending it to a web service(server), the code is shown below--->

client side

private void SendImage(byte[] data, long UserID)
{
    Uri uri = new Uri("some uri");
    IDictionary<string, object> bytesToSend = new Dictionary<string, object>();
    bytesToSend.Add("ImageBytes", Convert.ToBase64String(data));
    PostClient post = new PostClient(bytesToSend);
    post.DownloadStringAsync(uri);
}

server side

[HttpPost]
public bool SaveImage(object ImageBytes, Int64 UserID = 1)
{
    string ImgStr = ((string[])(ImageBytes))[0];
    byte[] ImgBytes = Convert.FromBase64String(ImgStr); ///<----///ERROR
    Image ItemImage;
    using (MemoryStream ms = new MemoryStream(ImgBytes))
    {
        ItemImage = Image.FromStream(ms);
    }
    PostUserItems(ItemImage);
    return true;
}

but at receiving end an error occurring

invalid length for a base 64 char array

joce
  • 9,624
  • 19
  • 56
  • 74
Ashok Damani
  • 3,896
  • 4
  • 30
  • 48

3 Answers3

0

Your data is coming in as a String, not a String[]. You can fix the cast, so instead of

string ImgStr = ((string[])(ImageBytes))[0];

do

string ImgStr = (string)ImageBytes;

If you can, change the function declaration since your function requires a String, not an Object.

public bool SaveImage(String ImgStr, Int64 UserID = 1)
{
    byte[] ImgBytes = Convert.FromBase64String(ImgStr);
    // ...
}
bmm6o
  • 6,187
  • 3
  • 28
  • 55
0

The length of a base64 encoded string is always a multiple of 4. If it is not a multiple of 4, then = characters are appended until it is. A query string of the form ?name=value has problems when the value contains = charaters (some of them will be dropped, I don't recall the exact behavior). You may be able to get away with appending the right number of = characters before doing the base64 decode.

Edit 1

You may find that the value of UserNameToVerify has had "+"'s changed to " "'s so you may need to do something like so;

a = a.Replace(" ","+"); This should get the length right;

int mod4 = a.Length % 4; if ( mod4 > 0 )

{

a += new string( '=', 4 - mod4 );

}

Of course calling UrlEncode (as in LukeH's answer) should make this all moot.

-1

I've seen this error caused by the combination of good sized viewstate and over aggressive content-filtering devices/firewalls (especially when dealing with K-12 Educational institutions).

We worked around it by storing Viewstate in SQL Server. Before going that route, I would recommend trying to limit your use of viewstate by not storing anything large in it and turning it off for all controls which do not need it.

References for storing ViewState in SQL Server: MSDN - Overview of PageStatePersister ASP Alliance - Simple method to store viewstate in SQL Server Code Project - ViewState Provider Model