将二进制文件字节数组发送到Web api方法

时间:2018-09-26 11:39:36

标签: c# winforms asp.net-web-api httpwebrequest

我需要将JSON或字节数组格式的大小为100MB的二进制文件发布到Web API 1.1。 我的客户端应用程序是具有x32位体系结构的C#winforms应用程序。我想从该客户端应用程序中读取二进制文件,然后将此二进制文件字节数组发送到Web API。

winforms应用程序中的当前实现如下

var sFile = @"C"\binary.zip";
var mybytearray = File.ReadAllBytes(sFile);
var webRequest =
                (HttpWebRequest)WebRequest.Create("http://localhost/filewriter");
webRequest.ContentType = "text/plain";
webRequest.Method = WebRequestMethods.Http.Post;
webRequest.AllowWriteStreamBuffering = true;
webRequest.Timeout = 100000;
webRequest.Headers.Add("fileName", Path.GetFileName(sFile));
webRequest.ContentLength = mybytearray.Length;

using (var dataStream = new StreamWriter(webRequest.GetRequestStream()))
      dataStream.Write(mybytearray);

using (var response = webRequest.GetResponse())
{
    if(response.StatusCode = HttpStatusCode.Ok;
         return true;
}

下面是用我的Web api方法编写的

[HttpPost]
public HttpResponseMessage filewriter(byte[] binaryData)
{
    using (FileStream binaryFileStream = new FileStream("C:\\myNewFile.zip", FileMode.Create, FileAccess.ReadWrite))
          {
              binaryFileStream.Write(binaryData, 0, binaryData.Length);
          }
}

如您所见,在上面的代码中,我无法将字节数组发送到Web api方法文件编写器。我是否缺少在这种情况下应该起作用的东西。

按照我说过的其他方法,我尝试过相同的方法,但是没有使用Json的字节数组,如下所示

var sFile = @"C"\binary.zip";   
var mybytearray = File.ReadAllBytes(sFile);
var mymodel = new model
{
    fileName = sFile,
    binaryData = mybytearray
};

var jsonResendObjects = JsonConvert.SerializeObject(mymodel);
var webRequest = (HttpWebRequest)WebRequest.Create("http://localhost/filewriter");
webRequest.ContentType = "application/json";
webRequest.Method = WebRequestMethods.Http.Post;
webRequest.AllowWriteStreamBuffering = true;
webRequest.Timeout = 100000;
webRequest.Headers.Add("fileName", Path.GetFileName(sFile));
webRequest.ContentLength = jsonResendObjects.Length;
byte[] responseData = null;

webRequest.AllowWriteStreamBuffering = true;
using (var dataStream = new StreamWriter(webRequest.GetRequestStream()))
    dataStream.Write(jsonResendObjects);

在网络api端

[HttpPost]
public HttpResponseMessage filewriter([FromBody]model mymodel)
{
    using (FileStream binaryFileStream = new FileStream("C:\\myNewFile.zip", FileMode.Create, FileAccess.ReadWrite))
          {
              binaryFileStream.Write(mymodel.binarydata, 0, binaryDatabinarydat.Length);
          }
}

1 个答案:

答案 0 :(得分:2)

  

根据我的说法,将base64编码用于   交流。

如果您想这样做

首先,将文件转换为byte [],然后转换为base64字符串

赞:

byte[] bytes = File.ReadAllBytes("path");
string file = Convert.ToBase64String(bytes);
// You have base64 Data in "file" variable

在您的WebAPI端点上接受字符串

[HttpPost]
public HttpResponseMessage filewriter(string fileData)
{
}

然后将您的base64字符串转换回byte []并将其写入文件或您要执行的任何操作。

赞这个:

// put your base64 string in b64str
Byte[] bytes = Convert.FromBase64String(b64Str);
File.WriteAllBytes(path, bytes);
  

您可以像这样使用GZIP压缩字符串

public static void CopyTo(Stream src, Stream dest) {
    byte[] bytes = new byte[4096];

    int cnt;

    while ((cnt = src.Read(bytes, 0, bytes.Length)) != 0) {
        dest.Write(bytes, 0, cnt);
    }
}

public static byte[] Zip(string str) {
    var bytes = Encoding.UTF8.GetBytes(str);

    using (var msi = new MemoryStream(bytes))
    using (var mso = new MemoryStream()) {
        using (var gs = new GZipStream(mso, CompressionMode.Compress)) {
            //msi.CopyTo(gs);
            CopyTo(msi, gs);
        }

        return mso.ToArray();
    }
}

public static string Unzip(byte[] bytes) {
    using (var msi = new MemoryStream(bytes))
    using (var mso = new MemoryStream()) {
        using (var gs = new GZipStream(msi, CompressionMode.Decompress)) {
            //gs.CopyTo(mso);
            CopyTo(gs, mso);
        }

        return Encoding.UTF8.GetString(mso.ToArray());
    }
}

参考:-

Convert file to base64 and back

GZip Compression