Search code examples
c#convertapi

How to convert a file into binary format for sending it inside a POST request payload


I'm trying to use this API, which converts files between different formats. As part of the request, it expects the file in Binary format. I'm trying to figure out exactly what that means when it comes to C#. Everything I've read points to using a byte array but that hasn't worked so far.

Essentially, I need to convert a document to binary and then use that raw data and plug it into another part of the system that's responsible for sending the actual POST request.

In an effort to understand the API better, I tested the endpoint and viewed the request payload. Chrome doesn't display the raw data that's sent as part of the File field:

Request Payload Screenshot

Fiddler does, but it's gibberish (probably because it attempts to interpret the bytes as ASCII):

enter image description here

So I'm a bit confused. For the purposes for that form-data object in the request payload, what do I need to do to the file I have in C#? I tried this (I'm accessing the file from another system using that system's API):

DocumentInfo di = this.BoundEntryInfo as DocumentInfo;
string contentType = "application/msword";
string binaryValue;

using (DocstarReadStream filestream = di.ReadDoc(out contentType)) //open a stream to the word document in the other system
{
    using (MemoryStream mstream = new MemoryStream())
    {
         filestream.CopyTo(mstream);
         binaryValue = string.Join("", mstream.ToArray());
    }
}

The resulting binaryValue string has a value like this:

807534200608000330223164210108901003250019082916711111011610111011695841211121011159346120109108321624240160020000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000018014820311019448166924714925015145183859823216217042213962150458223372412328625314619918825419019...

However, using this as the value of the File field in the POST request payload results in a Bad Request error (it says "conversion error" so I'm assuming the data is formatted wrong somehow).


Solution

  • Instead of converting the byte array to a string and sending that as the body, you should instead write the bytes to the request stream being sent through your HttpClient of choice. The content-type encoding is expecting you to send across the raw binary data as the payload, and has no idea what to do with the string interpretation.

    This is why the data in fiddler looks like gibberish. It is, as you suspected, a text representation of binary data.