12

Imgur is a image uploading website who offers an API to upload

My code looks exactly like the PHP code they provide as an example. however, in their php code they are http_build_query($pvars);

It seems like they are URLEncoding their query before posting it. edit: Note that I have changed to full .NET 3.5 rather then the client profile. This gave me access to system.web so I used httputliity.urlencode(). This made the api return a "fail" with a "no image was sent". If I don't encode then the API returns an "okay" with a link to the picture, however no picture is uploaded (like a blank file).

How can I fix my code to work properly against their API?

 Image image = Image.FromFile("C:\\Users\\Affan\\Pictures\\1509310.jpg");
        MemoryStream ms = new MemoryStream();
        // Convert Image to byte[]
        image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
        byte[] imageBytes = ms.ToArray();

        WebRequest wb = WebRequest.Create(new Uri("http://imgur.com/api/upload.xml"));
        wb.ContentType = "application/x-www-form-urlencoded";            
        wb.Method = "POST";
        wb.Timeout = 10000;
        Console.WriteLine(imageBytes.Length);
        string parameters = "key=433a1bf4743dd8d7845629b95b5ca1b4&image=" + Convert.ToBase64String(imageBytes);


        Console.WriteLine("parameters: " + parameters.Length);
        System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
        byte[] bytes = encoding.GetBytes(parameters);
        // byte[] bytes = Convert.FromBase64String(parameters);

        System.IO.Stream os = null;
        try { // send the Post
            wb.ContentLength = bytes.Length;   //Count bytes to send
            os = wb.GetRequestStream();               
            os.Write(bytes, 0, bytes.Length);         //Send it
        } catch (WebException ex) {
            MessageBox.Show(ex.Message, "HttpPost: Request error");
            Console.WriteLine(ex.Message);
        } finally {
            if (os != null) {
               // os.Close();
            }
        }

        try { // get the response
            WebResponse webResponse = wb.GetResponse();

            StreamReader sr = new StreamReader(webResponse.GetResponseStream());
            //MessageBox.Show(sr.ReadToEnd().Trim());
            Console.WriteLine(sr.ReadToEnd().Trim());
        } catch (WebException ex) {
            MessageBox.Show(ex.Message, "HttpPost: Response error");
        }       
p.campbell
  • 98,673
  • 67
  • 256
  • 322
masfenix
  • 7,736
  • 11
  • 45
  • 60
  • https://www.youtube.com/watch?v=XZxzJGgox_E -> Please don't put your app's key and id with your code. – N.K Feb 09 '18 at 16:26

3 Answers3

11

I've just uploaded this image

Hello World

using this code:

using (var w = new WebClient())
{
    var values = new NameValueCollection
    {
        { "key", "433a1bf4743dd8d7845629b95b5ca1b4" },
        { "image", Convert.ToBase64String(File.ReadAllBytes(@"hello.png")) }
    };

    byte[] response = w.UploadValues("http://imgur.com/api/upload.xml", values);

    Console.WriteLine(XDocument.Load(new MemoryStream(response)));
}

You might want to change your API key now :-)

The output was:

<rsp stat="ok">
  <image_hash>IWg2O</image_hash>
  <delete_hash>fQAXiR2Fdq</delete_hash>
  <original_image>http://i.imgur.com/IWg2O.png</original_image>
  <large_thumbnail>http://i.imgur.com/IWg2Ol.jpg</large_thumbnail>
  <small_thumbnail>http://i.imgur.com/IWg2Os.jpg</small_thumbnail>
  <imgur_page>http://imgur.com/IWg2O</imgur_page>
  <delete_page>http://imgur.com/delete/fQAXiR2Fdq</delete_page>
</rsp>
dtb
  • 213,145
  • 36
  • 401
  • 431
  • WOW, i spent almost 5 hours on that.. thankyou for that. Can you figure out why my way wasnt working though? – masfenix Jan 15 '10 at 17:48
  • Nice answer! I always love a 'less-is-more' solution. Granted, you went for the bare-bones with no error-checking, but even adding that back in... Yep, nice one. – JMD Jan 15 '10 at 17:57
  • 1
    Note that *imgur* changed to a new version of its API. The URI for the [version 2 anonymous API](http://api.imgur.com/resources_anon) is `http://api.imgur.com/2/upload`. The response XML has changed, but the C# code to make the request is apart from the URI the same. – dtb May 10 '12 at 00:16
  • 2
    They changed it to v3 now. Now it seems to require OpenAuth. Could you update your answer to reflect that? – Mathias Lykkegaard Lorenzen Oct 18 '13 at 20:20
10

Here's an updated version of dtb's answer for the v3 API using anonymous uploading (you need to register your app at http://api.imgur.com/ to get your client ID):

using (var w = new WebClient())
{
    string clientID = "<<INSERT YOUR ID HERE>>";
    w.Headers.Add("Authorization", "Client-ID " + clientID);
    var values = new NameValueCollection
    {
        { "image", Convert.ToBase64String(File.ReadAllBytes(@"hello.png")) }
    };

    byte[] response = w.UploadValues("https://api.imgur.com/3/upload.xml", values);

    Console.WriteLine(XDocument.Load(new MemoryStream(response)));
}

And the response is now like this (see http://api.imgur.com/models/image):

<data success="1" status="200">
    <id>SbBGk</id>
    <title/>
    <description/>
    <datetime>1341533193</datetime>
    <type>image/jpeg</type>
    <animated>false</animated>
    <width>2559</width>
    <height>1439</height>
    <size>521916</size>
    <views>1</views>
    <bandwidth>521916</bandwidth>
    <deletehash>eYZd3NNJHsbreD1</deletehash>
    <section/>
    <link>http://i.imgur.com/SbBGk.jpg</link>
</data>
SupSuper
  • 133
  • 2
  • 7
0

I Guess that the dtb solution is deprecated

    using (var w = new WebClient())
    {
        var values = new NameValueCollection
    {
        {"image", Convert.ToBase64String(imageData)},
        {"type", "base64"}
    };

        w.Headers.Add("Authorization", "Client-ID xxxxxxxxx");
       var response = w.UploadValues("https://api.imgur.com/3/image", values);
    }

another way to do:

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.imgur.com/3/image");
        request.Headers.Add("Authorization", "Client-ID xxxxxxx");
        request.Method = "POST";

        ASCIIEncoding enc = new ASCIIEncoding();
        string postData = Convert.ToBase64String(imageData);
        byte[] bytes = enc.GetBytes(postData);

        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = bytes.Length;

        Stream writer = request.GetRequestStream();
        writer.Write(bytes, 0, bytes.Length);

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Community
  • 1
  • 1
Igor Monteiro
  • 933
  • 1
  • 11
  • 29