Search code examples
restsharp

RestRequest.AddFileBytes posting corrupted files


I'm trying to POST image files to a service using RestRequest.AddFileBytes, however when I do this, the file seems to be corrupted. When I download it back, the filesize is ever so slightly off, and depending on the file type, it may appear to have the wrong extension or be uninterpretable (presumably b/c the header is messed up)

When I attempt to do the same thing with Postman it file is OK, so it would seem to be something with the way I'm posting the file. Please advise!

private static bool AddPageBytes(string user, string password, string documentId, string fileName, string contentType, byte[] bytes)
        {
            System.Console.WriteLine($"AddPageBytes documentId:{documentId}  fileName:{fileName} contentType:{contentType} bytes:{bytes.Length}");
            var client = new RestClient(BASE_URL);
            var request = new RestRequest("v1/document/{id}/page", Method.POST);

            request.AddUrlSegment("id", documentId);

            request.AddHeader("X-IntegrationServer-Username", user);
            request.AddHeader("X-IntegrationServer-Password", password);
            request.AddHeader("Content-Type", "application/octet-stream");

            request.AddHeader("X-IntegrationServer-FileSize", bytes.Length.ToString());

            request.AddHeader("X-IntegrationServer-Resource-Name", fileName);
            request.AddFileBytes(fileName, bytes, fileName, contentType);


            var response = client.Execute(request);

            return response.IsSuccessful;

        }

Solution

  • Woudln't you know it, like clockwork I banged my head for the better part of 2 days then posted this question and almost immediately figured out how to make it work. I wouldn't stay that I know why one is right and one is only mostly right (which is obviously not good enough) but

    I just had to change

    request.AddFileBytes(fileName, bytes, fileName, contentType);
    

    to

    request.AddParameter(contentType, bytes, ParameterType.RequestBody);