Hey, I'm currently trying to send an image file to a web server using a web request, a memory stream and an image object.
This is my current method for sending the request:
public void Send(Image image)
{
//Assign the request here too, just in case
Request = (HttpWebRequest)WebRequest.Create(FormURL);
Request.Method = "POST";
Request.ContentType = "multipart/form-data; boundary=" + CONTENT_BOUNDARY;
Request.Headers.Add("Cache-Control", "no-cache");
Request.KeepAlive = true;
Request.ContentLength = GetFormElements().Length +
GetFileHeader(FileName).Length +
FILE_TRAIL.Length +
ConvertImageToByteArray(image).Length;
//Must be done in this order for stream to write properly:
//----
//Form elements
//File header
//Image
//File trailer
//----
WriteStringToStream(FileStream, GetFormElements());
WriteStringToStream(FileStream, GetFileHeader(FileName));
WriteImageToStream(FileStream, image);
WriteStringToStream(FileStream, FILE_TRAIL);
string PostData = ASCIIEncoding.ASCII.GetString(ConvertImageToByteArray(image));
StreamWriter SW = new StreamWriter(Request.GetRequestStream(), Encoding.ASCII);
SW.Write(PostData);
GetRequestResponse();
Console.WriteLine(Request.HaveResponse);
FileStream.Close();
Request = null;
}
The problem I am having is that I'm not getting ANY response from the server at all, despite the stream being what looks to be a correct length (I removed some debug outputs from the code above)
If necessary, I can post other parts of my class, but for now here are the writing functions:
WriteStringToStream:
private void WriteStringToStream(System.IO.MemoryStream stream, string String)
{
byte[] PostData = System.Text.Encoding.ASCII.GetBytes(String);
stream.Write(PostData, 0, PostData.Length);
}
WriteImageToSteam:
private void WriteImageToStream(System.IO.MemoryStream Stream, Image img)
{
Stream.Write(ConvertImageToByteArray(img), 0, ConvertImageToByteArray(img).Length);
}
ConvertImageToByteArray:
private Byte[] ConvertImageToByteArray(Image img)
{
//Method taken from http://www.csharp-station.com/Articles/Thumbnails.aspx and adapted
MemoryStream memStream = new MemoryStream();
img.Save(memStream, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] byteArray = new Byte[memStream.Length];
memStream.Position = 0;
memStream.Read(byteArray, 0, (int)memStream.Length);
return byteArray;
}