如何将图像文件上传到imgur?

时间:2015-12-19 23:39:28

标签: c# image-uploading imgur

我正在尝试将图片上传到Imgur。我已经获取了客户端ID和客户端密钥,但是当我尝试上传数据时,会抛出异常。例外情况说"远程服务器返回错误。 400:糟糕的请求"。也许我的客户端ID是错误的,因为我不确定它是否是正确的密钥。我是从developers.google.com获得的,它是类型"其他"的OAuth客户端ID。我该如何解决这个问题?

我的代码:

        WebClient client = new WebClient();
        NameValueCollection values = new NameValueCollection();
        values["image"] = Convert.ToBase64String(File.ReadAllBytes(@"C:\Image.png"));
        values["key"] = myClientID;
        byte[] responseBytes = client.UploadValues("https://api.imgur.com/2/upload.xml", values);
        string response = Encoding.Default.GetString(responseBytes);
        client.Dispose();

        Console.WriteLine(XDocument.Load(new MemoryStream(responseBytes)));

        Console.ReadKey();
编辑:我刚刚意识到主要问题是因为客户端ID错误。因此,从https://api.imgur.com/oauth2/addclient获取新客户端ID可解决问题。上传的代码就像:

        using (var w = new WebClient())
        {
            var values = new NameValueCollection
            {
                {"image", Convert.ToBase64String(File.ReadAllBytes(imgPath))}
            };
            w.Headers.Add("Authorization", "Client-ID " + clid);
            byte[] response = w.UploadValues("https://api.imgur.com/3/upload.xml", values);

            Console.WriteLine(XDocument.Load(new MemoryStream(response)));
            //now process response as you'd like. the link is encapsulated by <link></link> in the response.
        }

0 个答案:

没有答案