Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Binary File Post Request

I am dealing with a third-party API which insists on a binary File Upload request being formatted without a Content-Type header value of multipart/form-data, and with the following headers:

Content-Type: application/octet-stream
Content-Disposition: filename*=UTF-8''file.zip

HttpRequestMessage and HttpContent.Headers.ContentDisposition.DispositionType won't allow me to achieve this either because I can't set the values as desired or they set them automatically.

I accept that this API may not be following HTTP Standards but it's not mine and I have no influence over it.

My attempt which does not work

    using (HttpClient client = new HttpClient())
    {
        client.DefaultRequestHeaders.ExpectContinue = false;
        FileStream fs = new FileStream(@"e:\dev\TestHalfB.docx", FileMode.Open);

        HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, <Uri>);
        HttpContent fc = new StreamContent(fs);
        var mpContent = new MultipartFormDataContent();
        mpContent.Add(fc);
        fc.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream");
        req.Content = fc;
        fc.Headers.ContentDisposition.DispositionType = "filename*=UTF-8''TestHalfB.docx";

        using (var response = await client.SendAsync(req))
        {
            response.EnsureSuccessStatusCode();
            var resp = await response.Content.ReadAsStringAsync();
        }

        fs.Close();
    }

Does anyone know of a lower level API I could use or have any suggestions?

So the crux is how can I set the Content-Disposition header to the value I desire.

like image 676
phil Avatar asked Oct 18 '25 11:10

phil


1 Answers

I had to switch to using WebRequest.

    WebRequest request = WebRequest.Create("https://cloud.memsource.com/web/api2/v1/projects/{id}/jobs?token={token}");
    request.Method = "POST";
    byte[] byteArray = File.ReadAllBytes(@"E:\Dev\TestHalfB.docx");
    request.ContentType = "application/octet-stream";
    request.ContentLength = byteArray.Length;
    request.Headers.Add("Content-Disposition", "filename*=UTF-8''TestHalfB.docx");
    Stream dataStream = request.GetRequestStream();
    dataStream.Write(byteArray, 0, byteArray.Length);
    dataStream.Close();
    WebResponse response = request.GetResponse();
    ((HttpWebResponse)response).StatusDescription.Dump();
like image 144
phil Avatar answered Oct 20 '25 01:10

phil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!