Search code examples
c#asp.netinputstream

ASP.NET - How to get file byte array from parameters in HttpContext.Request


There are two parts here. The client part is using HttpClient to pass parameters to server side. The server side is an ashx file. Client side code is as below.

HttpClient client = new HttpClient();

MultipartFormDataContent multipartContent = new MultipartFormDataContent();

if (!string.IsNullOrEmpty(attachFileName) && attachContent != null
 && attachContent.Length > 0)
{
    var imageBinaryContent = new ByteArrayContent(attachContent);

    multipartContent.Add(imageBinaryContent, attachFileName);

    multipartContent.Add(new StringContent(attachFileName), "attachFileName");
}

 multipartContent.Add(new StringContent("xxx"), "subject"); 

 var response = client.PostAsync(url, multipartContent).Result;

How can I get the file array in server part? I try to use below code to get file array, but the file is corrupt. I believe that the input stream must contains more data, not only the byte array.

 MemoryStream ms = new MemoryStream();

 context.Request.InputStream.CopyTo(ms);

 byte[] data = ms.ToArray();

How can I get the exact byte array of the file? Thanks.


Solution

  • I find a walk around solution. I hope it helps people who are also facing this issue. I didn't find good method to catch the byte array in HttpContext.Request. Then I decided to convert the byte array to base64 string before sending it out, and then convert the base64 string back to byte array in the server side.

    In client side, convert byte array to base64 string.

            HttpClient client = new HttpClient();
            MultipartFormDataContent multipartContent = new MultipartFormDataContent();
            if (!string.IsNullOrEmpty(attachFileName) && attachContent != null && attachContent.Length > 0)
            {
                multipartContent.Add(new StringContent(Convert.ToBase64String(attachContent)), attachFileName);
                multipartContent.Add(new StringContent(attachFileName), "attachFileName");
            }
            var response = client.PostAsync(url, multipartContent).Result;
    

    In server side, convert base64 string back to byte array.

            string attachFileName = context.Request.Form["attachFileName"];
            string fileBody = context.Request[attachFileName];
            byte[] data = null;
            if (!string.IsNullOrEmpty(attachFileName) && !string.IsNullOrEmpty(fileBody))
            {
                data = Convert.FromBase64String(fileBody);
            }