views:

142

answers:

1

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.

+4  A: 

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())));
Rubens Farias
I love this - because the C# version is actually shorter than the python version.
Aaronaught
I get an exception, and I think it's because I don't use my API key. Where would I insert my API key?
Sergio Tapia