Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

HttpWebRequest and multipart/form-data content type issue

Status
Not open for further replies.

CodingIsFun

Programmer
Apr 9, 2004
134
US
Hi all experts,

I am trying to send a multipart/form-data content to a page.

For some reason the following code is not posting to the url.

When I post to the URL the normal way using Type = File all works well.

Let me know if you see something irregular:

MemoryStream oPostStream = new MemoryStream();
BinaryWriter oPostData = new BinaryWriter(oPostStream);
string cMultiPartBoundary = "----------" + DateTime.Now.Ticks.ToString("x");
AddPostKey("body",Encoding.GetEncoding(1252).GetBytes(body),oPostData,cMultiPartBoundary);
AddPostKey("fromAddress",Encoding.GetEncoding(1252).GetBytes(fromAddress),oPostData,cMultiPartBoundary);
AddPostFile("fileAttachment",attachment_path,oPostData,cMultiPartBoundary);
oPostData.Write(Encoding.GetEncoding(1252).GetBytes("--" + cMultiPartBoundary + "\r\n"));

HttpWebRequest request = (HttpWebRequest) WebRequest.Create(docManagerUploadURL);
request.ContentType = "multipart/form-data; boundary=" + cMultiPartBoundary;
request.Method = "Post";
//*** Copy the Memory Stream to the Request Stream
Stream loPostData = request.GetRequestStream();
oPostStream.WriteTo(loPostData);


//*** Close the memory stream
oPostStream.Close();
oPostStream = null;

//*** Close the Binary Writer
oPostData.Close();
oPostData = null;

//*** Close Request Stream
loPostData.Close();

static void AddPostFile(string Key, string FileName, BinaryWriter oPostData, string cMultiPartBoundary)
{
byte[] lcFile;
FileStream loFile = new FileStream(FileName, FileMode.Open, FileAccess.Read);
lcFile = new Byte[loFile.Length];
loFile.Read(lcFile, 0, (int)loFile.Length);
loFile.Close();

oPostData.Write(Encoding.GetEncoding(1252).GetBytes("--" + cMultiPartBoundary + "\r\n" +
"Content-Disposition: form-data; name=\"" + Key + "\" filename=\"" +
new FileInfo(FileName).Name + "\"\r\n\r\n"));
oPostData.Write(lcFile);
oPostData.Write(Encoding.GetEncoding(1252).GetBytes("\r\n"));
}

static void AddPostKey(string Key, byte[] Value, BinaryWriter oPostData, string cMultiPartBoundary)
{

oPostData.Write(Encoding.GetEncoding(1252).GetBytes(
"--" + cMultiPartBoundary + "\r\n" +
"Content-Disposition: form-data; name=\"" + Key +
"\"\r\n\r\n"));

oPostData.Write(Value);

oPostData.Write(Encoding.GetEncoding(1252).GetBytes("\r\n"));
}

Any help would be greatly appreciated.

thanks in advance.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top