0

Here's the snippet:

Function Encode(ByVal dec As String) As String 

        Dim bt() As Byte 
        ReDim bt(dec.Length) 
        bt = System.Text.Encoding.ASCII.GetBytes(dec) 
        Dim enc As String 
        enc = System.Convert.ToBase64String(bt) 
        Return enc 
    End Function 

I'm trying to make an program that sends an image for upload to a website. Here's the code in Python, I'm trying to port it to C# but it's a bit confusing because I don't know any python.

#!/usr/bin/python

import pycurl

c = pycurl.Curl()
values = [
          ("key", "YOUR_API_KEY"),
          ("image", (c.FORM_FILE, "file.png"))]
# OR:     ("image", "http://example.com/example.jpg"))]
# OR:     ("image", "BASE64_ENCODED_STRING"))]

c.setopt(c.URL, "http://imgur.com/api/upload.xml")
c.setopt(c.HTTPPOST, values)

c.perform()
c.close()

Am I even supposed to be transforming the image.png file to a Base64 string? Please help.

Sergio Tapia
  • 40,006
  • 76
  • 183
  • 254
  • 4
    Are you trying to port the VB.NET method to C#, or the python script? – Aaronaught Jan 11 '10 at 00:37
  • The Python script is the working example given on the API Documentation Site. I'm looking for a way to convert the Python script to C#. A small piece of that (I think) is what I posted in Visual Basic, but I can't really understand what they're doing there because I'm not familiar with VB. – Sergio Tapia Jan 11 '10 at 00:42

1 Answers1

4

VB.NET to C#:

string Encode(string dec)
{
    return 
        Convert.ToBase64String(
            Encoding.ASCII.GetBytes(dec));
}

So you're talking about Python to C# (file upload):

WebClient wc = new WebClient();
wc.UploadFile("http://imgur.com/api/upload.xml", "POST", "file.png");

If you do need to set that fields name, probably this script is a better start, as it builds an request from scratch: Upload files with HTTPWebrequest (multipart/form-data)

Also, try this:

WebClient wc = new WebClient();
wc.UploadData(
    "http://imgur.com/api/upload.xml", "POST", 
    Encoding.UTF8.GetBytes(
        String.Join("&", 
            new Dictionary<string, string>()
            {
                { "key", "YOUR_API_KEY" },
                { "image", Convert.ToBase64String(File.ReadAllBytes("file.png"))}
            }.Select(item => 
                String.Format("{0}={1}", 
                    item.Key, HttpUtility.UrlEncode(item.Value)))
            .ToArray())));
Community
  • 1
  • 1
Rubens Farias
  • 57,174
  • 8
  • 131
  • 162