Gfycat API文件上传

时间:2016-10-17 18:48:13

标签: c# httpclient

我正在努力使用Gfytcat API从我的机器上传mp4。也许只是我,但API文档似乎没有很好地充实。

以下代码成功请求新的gfy,但上传失败并出现以下错误:204:No Content。

using (var client = new HttpClient())
{
    var response = await client.PostAsync(@"https://api.gfycat.com/v1/gfycats", null);

    var responseString = await response.Content.ReadAsStringAsync();

    var newGfycatResponse = Newtonsoft.Json.JsonConvert.DeserializeObject<NewGfycatResponse>(responseString);

    Console.WriteLine("gfyname: " + newGfycatResponse.gfyname);
    Console.WriteLine("secret: " + newGfycatResponse.secret);

    var filePath = @"C:\Users\Julien\Videos\black cat jumping.mp4";
    var file = File.ReadAllBytes(filePath);

    using (var content = new MultipartFormDataContent())
    {
        content.Add(new StringContent(newGfycatResponse.gfyname), "key");
        content.Add(new ByteArrayContent(file), "file", newGfycatResponse.gfyname);

        using (var message = await client.PostAsync("https://filedrop.gfycat.com", content))
        {
            var input = await message.Content.ReadAsStringAsync();

            Console.WriteLine(input);
        }
    }
}

1 个答案:

答案 0 :(得分:2)

看起来以下行不正确。您必须将字段命名为“file”,并将其命名为文件名。

content.Add(new StreamContent(new MemoryStream(file)), "file", newGfycatResponse.gfyname);

****编辑

您可能希望修改该文件内容的标题,如下所示。

下面的

取自:ASP.NET WebApi: how to perform a multipart post with file upload using WebApi HttpClient

var fileContent = new ByteArrayContent(System.IO.File.ReadAllBytes(fileName));
    fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
    {
        FileName = "Foo.txt"
    };
    content.Add(fileContent);