ASP.NET - 如何从 HttpContext.Request 中的参数获取文件字节数组

问题描述 投票:0回答:1

这里有两个部分。客户端部分使用

HttpClient
将参数传递给服务器端。服务器端是一个ashx文件。 客户端代码如下。

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;

如何获取服务器部分的文件数组?我尝试使用下面的代码来获取文件数组,但文件已损坏。我相信输入流必须包含更多数据,就像其他参数一样......

 MemoryStream ms = new MemoryStream();

 context.Request.InputStream.CopyTo(ms);

 byte[] data = ms.ToArray();

如何获取文件的确切字节数组?谢谢。

c# asp.net inputstream
1个回答
0
投票

我找到了一个解决方案。我希望它可以帮助那些也面临这个问题的人。我没有找到捕获 HttpContext.Request 中字节数组的好方法。然后我决定在发送出去之前将字节数组转换为base64字符串,然后在服务器端将base64字符串转换回字节数组。

在客户端,将字节数组转换为base64字符串。

        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;

在服务器端,将base64字符串转换回字节数组。

        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);
        }
© www.soinside.com 2019 - 2024. All rights reserved.