This blog is moved to
http://amalhashim.wordpress.com

Tuesday, July 8, 2008

Uploading and Downloading file using HttpWebRequest

Hi peoples,

Today am going to write two functions that will help to Upload & Download
files to and from another website.


public bool UploadFileEx(string fileName, string token, string url, string fileFormName, string contenttype, NameValueCollection querystring, CookieContainer cookies, byte[] fileBytes)
{
try
{
if ((fileFormName == null) ||(fileFormName.Length == 0))
{
fileFormName = "file";
}

if ((contenttype == null) ||(contenttype.Length == 0))
{
contenttype = "application/octet-stream";
}


string 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.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(fileName);
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);
byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
long length = postHeaderBytes.Length + fileBytes.Length + boundaryBytes.Length + 2;
webrequest.ContentLength = length;
Stream requestStream = webrequest.GetRequestStream();
requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
requestStream.Write(fileBytes, 0, fileBytes.Length);
boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
WebResponse responce = webrequest.GetResponse();
Stream s = responce.GetResponseStream();
StreamReader sr = new StreamReader(s);
string r = sr.ReadToEnd();
responce.Close();
return true;
}
catch(Exception ex)
{
return false;
}
}

Now Downloading

private bool DownloadFile(string arg)
{
try
{
string url = arg;
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
int bufferSize = 1
//Initialize the output stream
Response.Clear();
Response.AppendHeader("Content-Disposition:", "attachment; filename=" + args);
Response.AppendHeader("Content-Length", resp.ContentLength.ToString());
Response.ContentType = "application/download";
//Populate the output stream
byte[] ByteBuffer = new byte[bufferSize + 1];
MemoryStream ms = new MemoryStream(ByteBuffer, true);
Stream rs = req.GetResponse().GetResponseStream();
byte[] bytes = new byte[bufferSize + 1];
while (rs.Read(ByteBuffer, 0, ByteBuffer.Length) > 0)
{
Response.BinaryWrite(ms.ToArray());
Response.Flush();
}

//Cleanup
Response.End();
ms.Close();
ms.Dispose();
rs.Dispose();
ByteBuffer = null;
return true;
}
catch (Exception ex)
{
//File download failed;
return false;
}
}


Hope this will help you.

No comments: