Using HttpWebRequest for a Multipart POST

J

JB

Hello,

I am writing a method that performs a HTTP POST and sends two text
parameters and the third is an image that will be uploaded as part of the
HTTP POST. I can get the function to properly post the text parameters, but
the image shows up as an "X" like it is missing. It's not missing from the
path, I just believe that there is something wrong with the encoding or how
I am creating the boundary package. Here is the method; any help would be
appreciated.

protected string ExecutePostCommand(string filename, byte[] photo, string
text, string place)
{
HttpWebRequest request =
(HttpWebRequest)HttpWebRequest.Create(@"http://testdomain.com/api/post");
request.PreAuthenticate = true;
request.AllowWriteStreamBuffering = true;

string boundary = System.Guid.NewGuid().ToString();

if (!string.IsNullOrEmpty(Username) &&
!string.IsNullOrEmpty(Password))
{
request.Credentials = new NetworkCredential(Username, Password);
request.ContentType = string.Format("multipart/form-data;
boundary={0}", boundary);
request.Method = "POST";

// Build Contents for Post
string header = string.Format("--{0}", boundary);
string footer = header + "--";

StringBuilder contents = new StringBuilder();

// Image
contents.AppendLine(header);
contents.AppendLine(string.Format("Content-Disposition:
form-data; name=\"image\"; filename=\"{0}\"", filename));
contents.AppendLine("Content-Type: image/jpeg");
contents.AppendLine();
contents.AppendLine(Encoding.UTF8.GetString(photo));
// Text
contents.AppendLine(header);
contents.AppendLine("Content-Disposition: form-data;
name=\"text\"");
contents.AppendLine();
contents.AppendLine(text);
// Place
contents.AppendLine(header);
contents.AppendLine("Content-Disposition: form-data;
name=\"place\"");
contents.AppendLine();
contents.AppendLine(place);
// Footer
contents.AppendLine(footer);

// This is sent to the Post
byte[] bytes = Encoding.UTF8.GetBytes(contents.ToString());

request.ContentLength = bytes.Length;

using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Flush();
requestStream.Close();

using (WebResponse response = request.GetResponse())
{
using (StreamReader reader = new
StreamReader(response.GetResponseStream()))
{
return reader.ReadToEnd();
}
}
}
}

return null;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top