Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sending binary file byte array to web api method

I have a requirement to post binary file of size 100MB data in the format of either JSON or byte array to Web API 1.1. My client application is C# winforms application with x32 bit architecture. Where as I want to perform reading binary file from this client application and send this binary file byte array to Web API.

Current implementation in my winforms application is as below

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;
}

below is written at my Web api method

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

As you can see, in above code I was not able to send byte array to web api method filewriter. Am I missing something that should work in this case.

Other way as I said I was tried same but instead of byte array with Json one as below

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);

On web api side

[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);
          }
}
like image 948
CSharpDev Avatar asked Sep 26 '18 11:09

CSharpDev


1 Answers

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

If you want to do so

First, convert your file to byte[] and then to base64 string

Like this:

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

On your WebAPI Endpoint accept string

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

Then convert your base64 string back to byte[] and write it to file or whatever you want to do with that.

Like This:

// 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());
    }
}

Reference:-

Convert file to base64 and back

GZip Compression

like image 141
Mihir Dave Avatar answered Nov 14 '22 23:11

Mihir Dave