File Upload using HTTP POST - C#

After long war and blood shed I got it right
For anyone out there want to know how to upload files using HttpRequest -C#
BaseUrl = https://api.monday.com/v2/file

public async Task<FileUploadResponse> UploadFile() {
            string filePath = @"C:\Users\XYZ\Downloads\Dummy\001.docx";
            string fileName = Path.GetFileName(filePath);

            HttpClient httpClient = new HttpClient();
            httpClient.DefaultRequestHeaders.Add("Authorization", YOUR_TOKEN);
            httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("multipart/form-data"));

            MultipartFormDataContent form = new MultipartFormDataContent();
            byte[] file_bytes = File.ReadAllBytes(filePath);
            string query = @"mutation ($file: File!) 
                            {  
                                add_file_to_column(file: $file, item_id: XXYYZZ, column_id: ""files"")
                                {
                                    id
                                }
                            }";
            form.Add(new ByteArrayContent(file_bytes, 0, file_bytes.Length), "variables[file]", fileName);
            form.Add(new StringContent(query),"query");

            HttpResponseMessage response = await httpClient.PostAsync(BaseUrl, form);
            var stringResult = await response.Content.ReadAsStringAsync();
            response.EnsureSuccessStatusCode();
            return JObject.Parse(stringResult)["data"].ToObject<FileUploadResponse>();
        }


public class FileUploadResponse
    {
        [JsonProperty("data")]
        public Data Data { get; set; }

        [JsonProperty("account_id")]
        public int AccountId { get; set; }
    }

 public class AddFileToColumn
    {
        [JsonProperty("id")]
        public string Id { get; set; }
    }

    public class Data
    {
        [JsonProperty("add_file_to_column")]
        public AddFileToColumn AddFileToColumn { get; set; }
    }

Hi @mohamed.saleh!

Very impressive, thank you for sharing this with our community! I’m sure it will be put to good use.

I’ve moved this to our discussion section for now so that it can stay open and people can comment.

Thanks~

1 Like

That’s fine, I hope it helps someone out there.

2 Likes