Search code examples
.netfilehttpclient

HttpClient, PostAsync, File upload, boundary added to file body


I'm new to the forum so I'm not allowed to add the pictures directly. Neither am I allowed to add the tags "PostAsync" or "MultipartFormDataContent". Hope the url's work and that the post makes sense!

I'm using the HttpClient in a .NET console application to POST a file to an external web service. Currently I'm just working with a dummy-document (.txt) that looks like this: Original document

The POST works and uploads the document, but it has appended the boundary, content-disposition and content-type to the document text: Document after post

The code looks like this: code

If I look at the RequestMessage->Content the Headers looks ok to me: Content Header

My question is: Has this something to do with my POST, or could this be related to how the web service handles/receives the request? I've tried 4 different 'variations' (which are pretty much exactly the same) to do this POST with the same result. I also tried to remove the quotes from the boundary:

var boundaryValue = content.Headers.ContentType.Parameters.FirstOrDefault(p => p.Name == "boundary");

boundaryValue.Value = boundaryValue.Value.Replace("\"", String.Empty); 

Any input is appreciated, this has been bugging me for a while :)

EDIT

        string filePath = @"C:\Development\Customer\PKH\Documaster\TestFileToUpload.txt";
        // we need to send a request with multipart/form-data
        var content = new MultipartFormDataContent();
        var fileContent = new StreamContent(File.OpenRead(filePath));
        fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
        {
            Name = "\"files\"",
            FileName = "\"" + Path.GetFileName(filePath) + "\""
        };
        fileContent.Headers.ContentType = new MediaTypeHeaderValue("plain/text");
        content.Add(fileContent);

        //Create uri
        var builder = new UriBuilder(httpClient.BaseAddress + "integration/hub/v1/upload-single-file");
        var query = HttpUtility.ParseQueryString(builder.Query);
        var fileName = Path.GetFileName(filePath);
        query["file-name"] = fileName;
        builder.Query = query.ToString();
        string url = builder.ToString();

        //Do post
        try
        {
            HttpResponseMessage responseString = await httpClient.PostAsync(url, content);
            var contents = await responseString.Content.ReadAsStringAsync();
            JObject newDocument = JObject.Parse(contents);
            return newDocument;
        }
        catch(Exception)
        {
            return null;
        }

//Eivind


Solution

  • Nevermind, I figured this one out in the end: The receiving end expected to get an octet-stream, not multiform/data, so I just had to send this as a ByteArray and specify the MediaTypeHeaderValue instead:

    string filePath = @"C:\Development\Customer\PKH\Documaster\TestDocxToUpload.docx";
            var filebytes = File.ReadAllBytes(filePath);
    
            //Create uri
            var builder = new UriBuilder(httpClient.BaseAddress + "integration/hub/v1/upload-single-file");
            var query = HttpUtility.ParseQueryString(builder.Query);
            var fileName = Path.GetFileName(filePath);
            query["file-name"] = fileName;
            builder.Query = query.ToString();
            string url = builder.ToString();
    
            //Do post
            try
            {
                using (var content = new ByteArrayContent(filebytes))
                {
                    content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                    HttpResponseMessage responseString = await httpClient.PostAsync(url, content);
                    var contents = await responseString.Content.ReadAsStringAsync();
                    JObject newDocument = JObject.Parse(contents);
                    return newDocument;
                }
    
    
            }
            catch(Exception)
            {
                return null;
            }
    

    //Eivind