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; }
    }
1 Like

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

I tried the above c# code but it did not work for me, but in postman same thing was working and the RestSharp code postman generates also works in c#, what could be the reason?

var client = new RestClient("https://api.monday.com/v2/file");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", ApiKey);
request.AddParameter("query", "mutation ($file: File!) { add_file_to_column (file: $file, item_id: " + createdId + ", column_id: \"files\") { id } }");
request.AddFile("variables[file]", file_bytes, file.Name);
IRestResponse response = await client.ExecuteAsync(request);
Console.WriteLine(response.Content);

And here is my code similar to the above posted by author. What am I missing from the below code that the above code has?

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

var form = new MultipartFormDataContent();

string fileQuery = @"mutation ($file: File!) { add_file_to_column(file: $file, item_id: " + createdId + @", column_id: \""files\"") { id } }";

form.Add(new ByteArrayContent(file_bytes, 0, file_bytes.Length), "variables[file]", file.Name);
form.Add(new StringContent(query), "query");

var response = await httpClient.PostAsync("https://api.monday.com/v2/file", form);
var stringResult = await response.Content.ReadAsStringAsync();

The error I get with httpclient is {"error_message":"Unsupported query","status_code":400}

@umair

To be transparent with you, I am not a C# developer myself. That said, looking at the query you are using, and comparing it with the original post, it seems like you might not be inserting the File column ID correctly. Here’s what I mean:

  • Original post:

  • column_id: ""files""

  • Your code:

  • column_id: \""files\""

Perhaps that is causing the odd behavior here.

-Alex

Hi,

Did you manage to fix the error and get the file upload working using HttpClient. I am facing the issue.

Thanks

Hello there @Justin.Nagan and welcome to the community!

I hope you like it here :muscle:

Could you please elaborate on your particular issue?

Looking forward to hearing from you :slightly_smiling_face:

Cheers,
Matias

Thanks, I managed to resolve the issue building separate string. Passing the variable at the end of the string and then string concatenation for the next portion.

Hello @Justin.Nagan!

I am glad you could work it out :slightly_smiling_face:

We are here if you have any other questions!

Cheers,
Matias