I'm Implementing File upload into WCF Service using Client in asp .net
Here is the working code that can upload a file using a fixed size byte array carrying entire file.
protected void bUpload_Click(object sender, EventArgs e)
{
byte[] bytearray = null;
Stream stream;
string fileName = "";
//throw new NotImplementedException();
if (FileUpload1.HasFile)
{
fileName = FileUpload1.FileName;
stream = FileUpload1.FileContent;
stream.Seek(0, SeekOrigin.Begin);
bytearray = new byte[stream.Length];
int count = 0;
while (count < stream.Length)
{
bytearray[count++] = Convert.ToByte(stream.ReadByte());
}
}
string baseAddress = "http://localhost/WCFService/Service1.svc/FileUpload/";
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(baseAddress + fileName);
request.Method = "POST";
request.ContentType = "text/plain";
Stream serverStream = request.GetRequestStream();
serverStream.Write(bytearray, 0, bytearray.Length);
serverStream.Close();
try
{
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
int statusCode = (int)response.StatusCode;
System.Diagnostics.Debug.WriteLine("statusCode: " + statusCode);
StreamReader reader = new StreamReader(response.GetResponseStream());
System.Diagnostics.Debug.WriteLine("reader: " + reader.ToString());
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("--- EXCEPTION ---");
ex.ToString();
}
}
Then I changed writing 1024 bytes at a time and write in input stream, but with this getting response as
Exception (413) Request Entity Too Large
Here is the code that causes exception
request.Method = "POST";
request.ContentType = "text/plain";
// Stream serverStream = request.GetRequestStream();
if (FileUpload1.HasFile)
{
fileName = FileUpload1.FileName;
stream = FileUpload1.FileContent;
stream.Seek(0, SeekOrigin.Begin);
bytearray = new byte[1024];//stream.Length];
}
int TbyteCount = 0;
Stream requestStream = request.GetRequestStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int byteCount = 0;
while ((byteCount = stream.Read(buffer, 0, bufferSize)) > 0)
{
TbyteCount = TbyteCount + byteCount;
requestStream.Write(buffer, 0, byteCount);
}
requestStream.Close();
try
{
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
int statusCode = (int)response.StatusCode;
System.Diagnostics.Debug.WriteLine("statusCode: " + statusCode);
StreamReader reader = new StreamReader(response.GetResponseStream());
System.Diagnostics.Debug.WriteLine("reader: " + reader.ToString());
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("--- EXCEPTION ---");
ex.ToString();
}
}
Thanks in advance
~Ashok