BalihooBlipDotNet.S3Request.PostFile C# (CSharp) Method

PostFile() private static method

Create Multipart form-data HTTP Post to upload file to S3.
private static PostFile ( string s3Bucket, string formData, string mimeType, byte compressedFile ) : BlipResponse
s3Bucket string The Amazon S3 bucket name.
formData string The JSON object containing the pre-signed URL data.
mimeType string The MIME type of the file to be uploaded.
compressedFile byte The gzipped file contents.
return BlipResponse
        private static BlipResponse PostFile(string s3Bucket, string formData, string mimeType, byte[] compressedFile)
        {
            HttpResponseMessage response;
            dynamic data = JsonConvert.DeserializeObject(formData);

            using (var client = new HttpClient())
            {
                var url = $"https://s3.amazonaws.com/{s3Bucket}";
                var requestContent = new MultipartFormDataContent();
                var fileContent = new ByteArrayContent(compressedFile);
                fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse(mimeType);
                
                // Special parsing required due to a hyphen in the key
                string contentMd5 = JObject.Parse(data.ToString())["content-md5"];

                requestContent.Add(new StringContent(data.acl.ToString()), "acl");
                requestContent.Add(new StringContent(data.bucket.ToString()), "bucket");
                requestContent.Add(new StringContent(data.key.ToString()), "key");
                requestContent.Add(new StringContent(contentMd5), "content-md5");
                requestContent.Add(new StringContent(data.policy.ToString()), "policy");
                requestContent.Add(new StringContent(data.signature.ToString()), "signature");
                requestContent.Add(new StringContent(data.AWSAccessKeyId.ToString()), "AWSAccessKeyId");
                requestContent.Add(new StringContent(mimeType), "content-type");
                requestContent.Add(fileContent, "file"); // The file must be added last
                
                response = client.PostAsync(url, requestContent).Result;
            }

            var statusCode = (int)response.StatusCode;

            // If the upload is not successful return the error message from S3 else return success response
            return statusCode != 204 ? new BlipResponse(statusCode, response.Content.ToString()) : new BlipResponse(statusCode, "");
        }