簡體   English   中英

如何使用httpclient c#將文件上傳到ASANA api中的任務

[英]how to upload a file to a task in ASANA api using httpclient c#

我試圖通過HttpClient將文件附加到Asana中的任務,我收到一個錯誤:

{"errors":[{"message":"file: Missing input","help":"For more information on API status codes and how to handle them, read the docs on errors: https://asana.com/developers/documentation/getting-started/errors"}]}

我正在提出的請求具有以下格式。

static async void GoPost(byte[] image)
    {
        string ApiKey = "<API_KEY>";

        HttpClient httpClient = new HttpClient();
        httpClient.DefaultRequestHeaders.Accept.Clear();
        httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "Bearer " + ApiKey);
        MultipartFormDataContent form = new MultipartFormDataContent("Upload----");


        form.Add(new ByteArrayContent(image, 0, image.Length), "profile_pic", "1.png");
        HttpResponseMessage response = await httpClient.PostAsync("https://app.asana.com/api/1.0/tasks/<TASK_ID>/attachments", form);

        var input = await response.Content.ReadAsStringAsync();
        Console.WriteLine(input);
    }

有人可以幫忙嗎?

找到了解決方案

    public async Task<string> AttachFile(string file, string fileName, string id)
    {
        var decoded = Convert.FromBase64String(file);

        HttpClient httpClient = new HttpClient();
        httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "Bearer " + ApiKey);

        httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "multipart/form-data");

        MultipartFormDataContent form = new MultipartFormDataContent();

        var fileCont = new ByteArrayContent(decoded, 0, decoded.Length);
        fileCont.Headers.Add("Content-Disposition", $"form-data; name=\"file\"; filename=\"{fileName}\"");
        form.Add(fileCont);

        HttpResponseMessage response = await httpClient.PostAsync($@"https://app.asana.com/api/1.0/tasks/{id}/attachments", form);
        var responseData = await response.Content.ReadAsStringAsync();

        if (response.IsSuccessStatusCode)
            return "file was uploaded successfully";

        throw new ArgumentException($"Error code: {response.StatusCode}; {responseData}");
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM