如何使用HttpClient在ASANA API中上传文件到任务

3

我正在尝试通过 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);
    }

有人可以帮忙吗?


可能,如果您告诉我们实际的错误是什么?只说“我遇到了一个错误”对任何人都没有用。 - Steve
将其添加到您的问题中,而不是评论中。 - Steve
1个回答

0

找到了解决方案

    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}");
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接