Upload Images to ImageShack using Vb.net (or C#)
-
Tuesday, September 11, 2007 12:13 AM
Hi , this is a very newbie question but I have been trying to make it work and I still don't know how to do it,
I'm trying to upload images to imageshack.us using Vb.net but I really don't understand their API
Their API says:
Send the following variables via POST to http://www.imageshack.us/index.php
- fileupload; (the image)
- xml = "yes"; (specifies the return of XML)
- cookie; (registration code, optional)
they even provide a PHP example code (http://reg.imageshack.us/xmlapi.zip), I can't read it but It's very short so I guess it won't be hard to do it in .NET.
I have used POST before but I don't know how to handle the image here, I used this but it doesn't work,
Dim img As String = IO.File.ReadAllText(Me.ImagePath)
Dim URL As String = "http://www.imageshack.us/index.php?fileupload=" & img& "&xml=yes"
Dim req As HttpWebRequest = DirectCast(HttpWebRequest.Create(URL), HttpWebRequest)
Dim res As Net.HttpWebResponse = Nothing
req.Method = "POST"
req.ContentLength = URL.Length
req.KeepAlive = True
req.Timeout = 30000
res = CType(req.GetResponse, Net.HttpWebResponse)
Dim response As IO.StreamReader = New IO.StreamReader(res.GetResponseStream, System.Text.Encoding.UTF8)
Dim line As String
line = response.ReadLinethanks for your help and sorry if I'm doing something terribly wrong here I really don't have a enough knowledge about Networking
All Replies
-
Tuesday, September 11, 2007 5:59 AMIf you look at the sample code in the msdn, you'll find that you have to write the data into the requeststream first.. Anyway, personally i find that the WebClient class and it's (Begin) UploadFile methods are a lot easier to use...
-
Thursday, September 13, 2007 11:55 PM
I tryied loading the file data in the request stream but it still doesn't work, can please somebody tell me what I'm doing wrong?
Dim postDataFileStream As New FileStream(Me.ImagePath, FileMode.Open, FileAccess.Read)
Dim postDataMemoryStream As New MemoryStream(CInt(postDataFileStream.Length))
Dim br As BinaryReader
br = New BinaryReader(postDataFileStream)
Dim bytesRead As Byte() = br.ReadBytes(CInt(postDataFileStream.Length))
postDataMemoryStream.Write(bytesRead, 0, CInt(postDataFileStream.Length))Dim URL As String = "http://www.imageshack.us/index.php?fileupload=" & Me.ImagePath & "&xml=yes"
Dim req As HttpWebRequest = DirectCast(WebRequest.Create(url), HttpWebRequest)
req.Method = "POST"
req.ContentLength = CLng(postDataMemoryStream.Length)
Using s As Stream = req.GetRequestStream()
s.Write(postDataMemoryStream.ToArray(), 0, CInt(postDataMemoryStream.Length))
postDataMemoryStream.Close()
End Using
Dim res As Net.HttpWebResponse = Nothing
res = CType(req.GetResponse, Net.HttpWebResponse)
Dim response As IO.StreamReader = New IO.StreamReader(res.GetResponseStream, System.Text.Encoding.UTF8)
Dim line As String
line = response.ReadLine -
Friday, September 14, 2007 5:34 AM
ok I think that I have found the solution:
I didn't used webrequest in the end, I used this couple of articles:
http://www.codeproject.com/csharp/UploadFileEx.asp
http://www.anappaday.com/downloads/2006/10/day-19-jedi-image-shacker.html
I took some pieces of code of each and built a small class that handles the imageshack uploads and return the html response. here is it: (it's almost a complete copy paste of the articles above, with a small changes)
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Collections.Specialized;namespace ImageShackUploader
{
public class Uploader
{public string UploadFileToImageShack(object oFileName)
{
try
{
string fileName = oFileName as string;
string contentType = null;
CookieContainer cookie = new CookieContainer();
NameValueCollection col = new NameValueCollection();
col["MAX_FILE_SIZE"] = "3145728";
col["refer"] = "";
col["brand"] = "";
col["optimage"] = "1";
col["rembar"] = "1";
col["submit"] = "host it!";
List<string> l = new List<string>();
switch (fileName.Substring(fileName.Length - 3, 3))
{
case "jpg":
contentType = "image/jpeg";
break;
case "peg":
contentType = "image/jpeg";
break;
case "gif":
contentType = "image/gif";
break;
case "png":
contentType = "image/png";
break;
case "bmp":
contentType = "image/bmp";
break;
case "tif":
contentType = "image/tiff";
break;
case "iff":
contentType = "image/tiff";
break;
default:
contentType = "image/unknown";
break;
}string resp;
col["optsize"] = "resample";
resp = UploadFileEx(fileName,
"http://www.imageshack.us/index.php",
"fileupload",
contentType,
col,
cookie);
return resp;
}
catch (Exception ex)
{
return "";
}
}public static string UploadFileEx(string uploadfile, string url,
string fileFormName, string contenttype, System.Collections.Specialized.NameValueCollection querystring,
CookieContainer cookies)
{
if ((fileFormName == null) ||
(fileFormName.Length == 0))
{
fileFormName = "file";
}if ((contenttype == null) ||
(contenttype.Length == 0))
{
contenttype = "application/octet-stream";
}
string postdata;
postdata = "?";
if (querystring != null)
{
foreach (string key in querystring.Keys)
{
postdata += key + "=" + querystring.Get(key) + "&";
}
}
Uri uri = new Uri(url + postdata);
string boundary = "----------" + DateTime.Now.Ticks.ToString("x");
HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(uri);
webrequest.CookieContainer = cookies;
webrequest.ContentType = "multipart/form-data; boundary=" + boundary;
webrequest.Method = "POST";
// Build up the post message header
StringBuilder sb = new StringBuilder();
sb.Append("--");
sb.Append(boundary);
sb.Append("\r\n");
sb.Append("Content-Disposition: form-data; name=\"");
sb.Append(fileFormName);
sb.Append("\"; filename=\"");
sb.Append(Path.GetFileName(uploadfile));
sb.Append("\"");
sb.Append("\r\n");
sb.Append("Content-Type: ");
sb.Append(contenttype);
sb.Append("\r\n");
sb.Append("\r\n");string postHeader = sb.ToString();
byte[] postHeaderBytes = Encoding.UTF8.GetBytes(postHeader);// Build the trailing boundary string as a byte array
// ensuring the boundary appears on a line by itself
byte[] boundaryBytes =
Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");FileStream fileStream = new FileStream(uploadfile,
FileMode.Open, FileAccess.Read);
long length = postHeaderBytes.Length + fileStream.Length +
boundaryBytes.Length;
webrequest.ContentLength = length;Stream requestStream = webrequest.GetRequestStream();
// Write out our post header
requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);// Write out the file contents
byte[] buffer = new Byte[checked((uint)Math.Min(4096,
(int)fileStream.Length))];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
requestStream.Write(buffer, 0, bytesRead);// Write out the trailing boundary
requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
WebResponse responce = webrequest.GetResponse();
Stream s = responce.GetResponseStream();
StreamReader sr = new StreamReader(s);return sr.ReadToEnd();
}
}
}To use it in vb you should do this:
Net.ServicePointManager.Expect100Continue = False
Dim dlgopenfile As New OpenFileDialog
dlgopenfile.ShowDialog()
If dlgopenfile.FileName <> "" Then
Dim i As New ImageShackUploader.Uploader
Me.TextBox1.Text = i.UploadFileToImageShack(dlgopenfile.FileName)
End If -
Sunday, September 16, 2007 4:31 AM
here is a nice class writen in vb, to upload images to imageshack, It may be useful to someone else:
Public Class ImageShackUploader
Structure ReturnedURLs
Dim DirectLinkURL As String
Dim ShowToFriendsURL As String
Dim ThumbnailURL As String
Dim Exitoso As Boolean
End Structure
Private Function GetReturnedURLsFromHTMLRta(ByVal HTML As String) As ReturnedURLsDim RtaURLs As New ReturnedURLs
RtaURLs.Exitoso = True
Dim ValueMatchString As String = "value=""(?<val>.*?)"""For Each m As System.Text.RegularExpressions.Match In _
System.Text.RegularExpressions.Regex.Matches(HTML, "<input type=""text"".*?/>", _
System.Text.RegularExpressions.RegexOptions.Singleline)If System.Text.RegularExpressions.Regex.IsMatch(m.Value, ValueMatchString) Then
Dim valuemath As System.Text.RegularExpressions.Match = System.Text.RegularExpressions.Regex.Match(m.Value, ValueMatchString)
Dim URLIMGMatch As System.Text.RegularExpressions.Match = _
System.Text.RegularExpressions.Regex.Match(valuemath.Groups("val").Value, "\\\")
If URLIMGMatch.Value <> "" Then
If URLIMGMatch.Groups("url").Value.ToLower = "http://imageshack.us" Then
RtaURLs.DirectLinkURL = URLIMGMatch.Groups("img").Value
Else
RtaURLs.ThumbnailURL = URLIMGMatch.Groups("img").Value
RtaURLs.ShowToFriendsURL = URLIMGMatch.Groups("url").Value
End If
End If
End IfNext
Return RtaURLs
End Function
Public Function UploadFileToImageShack(ByVal FileName As String) As ReturnedURLs
Dim OldValue As Boolean = System.Net.ServicePointManager.Expect100ContinueTry
System.Net.ServicePointManager.Expect100Continue = False
'1. Cookie
Dim Cookie As New Net.CookieContainer()'2. Arguments
Dim QueryStringArguments As New Dictionary(Of String, String)
QueryStringArguments.Add("MAX_FILE_SIZE", "3145728")
QueryStringArguments.Add("refer", "")
QueryStringArguments.Add("brand", "")
QueryStringArguments.Add("optimage", "1")
QueryStringArguments.Add("rembar", "1")
QueryStringArguments.Add("submit", "host it!")
QueryStringArguments.Add("optsize", "resample")'3. contentType
Dim ContentType As String = ""
Select Case IO.Path.GetExtension(FileName).ToLower
Case ".jpg"
ContentType = "image/jpeg"
Case ".jpeg"
ContentType = "image/jpeg"
Case ".gif"
ContentType = "image/gif"
Case ".png"
ContentType = "image/png"
Case ".bmp"
ContentType = "image/bmp"
Case ".tif"
ContentType = "image/tiff"
Case ".tiff"
ContentType = "image/tiff"
Case Else
ContentType = "image/unknown"
End Select'4. Upload and return Rta
Return GetReturnedURLsFromHTMLRta(UploadFileEx(FileName, "http://www.imageshack.us/index.php", "fileupload", ContentType, QueryStringArguments, Cookie))
Catch ex As Exception
Dim Rta As New ReturnedURLs
Rta.Exitoso = False
Return Rta
Finally
System.Net.ServicePointManager.Expect100Continue = OldValue
End Try
End Function
Private Function UploadFileEx(ByVal FileName As String, ByVal URL As String, ByVal FileFormName As String, ByVal ContentType As String, ByVal QueryStringArguments As Dictionary(Of String, String), ByVal Cookies As Net.CookieContainer) As StringIf FileFormName = "" Then FileFormName = "file"
If ContentType = "" Then ContentType = "application/octet-stream"Dim PostData As String = "?"
If QueryStringArguments IsNot Nothing Then
For Each kvp As KeyValuePair(Of String, String) In QueryStringArguments
PostData &= kvp.Key & "=" & kvp.Value & "&"
Next
End If
Dim URI As New Uri(URL + PostData)
Dim Boundary As String = "----------" + DateTime.Now.Ticks.ToString("x")
Dim WReq As Net.HttpWebRequest = DirectCast(Net.WebRequest.Create(URI), Net.HttpWebRequest)
WReq.CookieContainer = Cookies
WReq.ContentType = "multipart/form-data; boundary=" + Boundary
WReq.Method = "POST"Dim PostHeader As String = String.Format("--" & Boundary & "{0}" & _
"Content-Disposition: form-data; name=""" & FileFormName _
& """; filename=""" & IO.Path.GetFileName(FileName) & """{0}" _
& "Content-Type: " & ContentType & "{0}{0}", vbNewLine)Dim PostHeaderBytes As Byte() = System.Text.Encoding.UTF8.GetBytes(PostHeader)
Dim BoundaryBytes As Byte() = System.Text.Encoding.ASCII.GetBytes(vbNewLine & "--" + Boundary + vbNewLine)Dim FileStream As New IO.FileStream(FileName, IO.FileMode.Open, IO.FileAccess.Read)
WReq.ContentLength = PostHeaderBytes.Length + FileStream.Length + BoundaryBytes.Length
Dim RequestStream As IO.Stream = WReq.GetRequestStream()
RequestStream.Write(PostHeaderBytes, 0, PostHeaderBytes.Length)
Dim buffer As Byte() = New Byte(CInt(Math.Min(4096, CInt(FileStream.Length))) - 1) {}
Dim bytesRead As Integer = 0
Do
bytesRead = FileStream.Read(buffer, 0, buffer.Length)
If bytesRead = 0 Then Exit Do
RequestStream.Write(buffer, 0, bytesRead)
Loop
RequestStream.Write(BoundaryBytes, 0, BoundaryBytes.Length)Dim Rta As Net.WebResponse = WReq.GetResponse()
Dim s As IO.Stream = Rta.GetResponseStream()
Dim sr As New IO.StreamReader(s)Return sr.ReadToEnd()
End Function
End Class -
Tuesday, October 28, 2008 10:31 PMThis code works beautifully for me. The only problem is, my whole UI freezes for the 5-10 seconds Imageshack takes to return some xml to me. I would like to make the request asynchronous using webrequest.BeginGetRequestStream instead of webrequest.GetRequestStream, however I am at a loss as to how I'll start. Does anyone have experience translating a synchronous web request to an asynchronous web request? Thanks for your help.
Bradford
-
Thursday, December 18, 2008 9:14 AM
The UploadFileEx is ok but when I try to read Response, I get this exception:
"The response for this request cannot be retrieved until request data has been written."
To solve the issue I have modified the UploadFileEx:
// Write out the trailing boundary
requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
// NEW CODE
requestStream.Flush();
requestStream.Close();
WebResponse responce = webrequest.GetResponse();
Stream s = responce.GetResponseStream();
StreamReader sr = new StreamReader(s);
Also, I think that you make sure that the uploaded fileStream is closed:
fileStream.Close();
GV -
Tuesday, January 13, 2009 1:41 PMI am beginer in programing but i want to learn it !!!
What should be added on FORM1 to the BUTTON 3(and when i click that BUTTON) he started to upload pictures from PICTUREBOX1?
Thanks and sorry for bad ENG
AC Milan -
Sunday, June 14, 2009 7:57 AMI realise this thread is getting a little old, but for the benefit of others who find the thread through search, I've recently created a C# library that wraps the ImageShack API that only requires a simple method call to upload images. It's available at http://www.codeemporium.com/2009/06/14/dot-net-c-sharp-wrapper-for-the-imageshack-xml-api/. There's also a demo app included that uses the library, as well as source code for everything. Hope this can be of some help.Cheers, Bryce.
-
Tuesday, December 06, 2011 3:38 PM
Hi friend i got the error while uploading the image file
error is "The remote server returned an error: (404) Not Found." (WebException Caught)

