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

sending binary file byte array to web api method

我需要 post 大小为 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;
}

下面是我在网上写的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);
          }
}

According to me, it would be easy to use base64 encoding for communication.

如果你想这样做

首先,将您的文件转换为 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);

And you can Compress your string Using GZIP Like this

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