Sunday, June 13, 2010

ImageShack.us image upload (C# code)

Spent a couple hours yesterday looking for some code to upload images to ImageShack.us (I need it for a XBMC for Xbox remote control app I’m writting) and thought I might share the code.

The image I have is already available in a PictureBox and this only concentrates on the upload itself, won’t go into parsing the XML reply, that should be fairly easy to implement it yourself…

More information about the ImageShack.us Upload API and how to apply for a key here:
http://code.google.com/p/imageshackapi/wiki/ImageshackAPI

Working example here:
https://code.google.com/p/dandar3-apps/source/browse/#svn/trunk/ImageShack Upload

/**
 * ImageShack Unified upload API
 * http://code.google.com/p/imageshackapi/wiki/ImageshackAPI
 */
private void buttonUpload_Click(object sender, EventArgs e)
{
  //
  Cursor.Current = Cursors.WaitCursor;

  //
  // Init
  //
  String      filename    = "fake_name";
  String      mimeType    = "image/jpeg";
  ImageFormat imageFormat = System.Drawing.Imaging.ImageFormat.Jpeg;

  //
  // Prepare POST contents...
  //
  MemoryStream memoryStream = new MemoryStream();

  // Parts boundary
  String boundary = "-------" + DateTime.Now.Ticks.ToString("x");
  String crlf     = "\r\n";
  
  // Image file...
  write(memoryStream, "--" + boundary + crlf);
  write(memoryStream, String.Format("Content-Disposition: form-data; name=\"fileupload\"; filename=\"{0}\"", filename) + crlf);
  write(memoryStream, String.Format("Content-Type: {0}", mimeType) + crlf);
  write(memoryStream, crlf);
  
  pictureBox.Image.Save(memoryStream, imageFormat);
  write(memoryStream, crlf);
  
  // Other parameters (Key, Username, Password etc)
  NameValueCollection parameters = new NameValueCollection();
  parameters.Add("key",        "your_key");
  parameters.Add("a_username", "your_username");
  parameters.Add("a_password", "your_password");
  parameters.Add("tags",       "your_tags");

  foreach (String param_name in parameters.Keys)
  {
    write(memoryStream, "--" + boundary + crlf);
    write(memoryStream, String.Format("Content-Disposition: form-data; name=\"{0}\"", param_name) + crlf);
    write(memoryStream, crlf);
    write(memoryStream, parameters.Get(param_name));
    write(memoryStream, crlf);
  }

  // End...
  write(memoryStream, "--" + boundary + crlf);
  
  //
  // Upload (POST)...
  //
  try
  {
    HttpWebRequest webRequest = (HttpWebRequest) HttpWebRequest.Create("http://www.imageshack.us/upload_api.php");
    webRequest.ContentType    = "multipart/form-data; boundary=" + boundary;
    webRequest.Method         = "POST";

    //
    // Request
    //
    webRequest.ContentLength = memoryStream.Length;
    using (Stream requestStream = webRequest.GetRequestStream())
    {
      memoryStream.Seek(0, SeekOrigin.Begin);
      memoryStream.WriteTo(requestStream);
    }

    //
    // Response
    //
    using (WebResponse  webResponse  = webRequest.GetResponse())
    using (StreamReader streamReader = new StreamReader(webResponse.GetResponseStream()))
    {
      String imageshackReply = streamReader.ReadToEnd().Trim();
      MessageBox.Show(imageshackReply, "HTTP POST Response", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
  }
  catch (Exception ex)
  {
    MessageBox.Show(ex.Message, "HTTP POST Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
  }

  //
  // Clean-up...
  //
  memoryStream.Close();
}

/**
 * 
 */
private void write(MemoryStream p_memoryStream, String p_data)
{
  byte[] bytes = Encoding.ASCII.GetBytes(p_data);
  p_memoryStream.Write(bytes, 0, bytes.Length);
}

8 comments :

  1. Thanks bro...its very helpful for me...as
    keep up the good work!!

    Kalum Fernando(Computer Engineer

    ReplyDelete
  2. You're welcome, glad it's been useful.

    ReplyDelete
  3. Bro, It can't return in XML format?

    ReplyDelete
  4. Dude, you want me to chew it down for you? :) There's literally thousands of example on the web how to parse XML in C#, just google it.

    using (XmlDocument xmlDocument = new XmlDocument())
    {
    xmlDocument.Load(streamReader);
    XmlNode nodeImageLink = xmlDocument.GetElementsByTagName("image_link")[0];
    String imageLink.Text = nodeImageLink.InnerText;
    }

    ReplyDelete
  5. I knew how to parse XML, but from the code you provided it not return me XML for but as below:
    "0 0.0 sinchew.jpg sinchew.th.jpg 800 513 1 r no 175.139.247.61 http://img830.imageshack.us/img830/5255/sinchew.jpg < a href="http://img830.imageshack.us/i/sinchew.jpg/" target="_blank">< img src="http://img830.imageshack.us/img830/5255/sinchew.jpg..."

    ReplyDelete
  6. it seems that is no longer working. I received the following result:

    \ n No file was uploaded or empty file was uploaded \ n

    Can you help me? I really need this working.

    ReplyDelete
  7. Might be, I see there's a new API. Let me see if I can fix this and might prepare a sample project later on today.

    ReplyDelete
  8. There you go, see the link at the top for a working project, I also simplified the code a bit.

    ReplyDelete