Search This Blog

Thursday, October 18, 2012

Upload Large Image Using WCF Services Using RESTFul WCF Services

How to upload large image in WCF service?
By default WCF service allow 64KB data to upload if you want to upload more data then 64K you need to change the configuration settings, need to change the buffer size for incoming and outgoing request size here is an example for upload large image through WCF service,

In IService Interface, declare method.

here Method is POST and we are using stream to upload a image.

[OperationContract]
[WebInvoke(Method = "POST",UriTemplate = "/File")]
bool UploadImage(Stream obStream);

In Service implement interface method.

public bool UploadImage(Stream image)
{

 
if(image != null)

try
{

string ImageName = DateTime.Now.ToString().Replace(" ","").Replace(":","").Replace("/","") + ".jpeg";//define name of image.

if(!Directory.Exists(@"C:\Images"))//check folder exist or not.
Directory.CreateDirectory(@"C:\Images");
string strFilePath = @"C:\Images\" + ImageName;
FileStream targetStream = null;
Stream sourceStream = image;
string uploadFolder = @"C:\Images\";
string filename = ImageName;

string filePath = Path.Combine(uploadFolder,filename);
///write file using stream.
using(targetStream = new FileStream(filePath,FileMode.Create,FileAccess.Write,FileShare.None))
{

const int bufferLen = 4096;
byte[] buffer = new byte[bufferLen];
int count = 0;
int totalBytes = 0;
while((count = sourceStream.Read(buffer,0,bufferLen)) > 0)
{

totalBytes+=count;

Debug.WriteLine("Bytes Count="+totalBytes.ToString());
targetStream.Write(buffer,0,count);

}

targetStream.Close();

sourceStream.Close();

}

return true;
}

catch(Exception ex)
{

return false;
}

}

return false;
}

private byte[] StreamToByte(Stream stream)
{

   
byte[] buffer = new byte[16 * 1024];
    using(MemoryStream ms = new MemoryStream())
    {

    
int read;

     while((read = stream.Read(buffer,0,buffer.Length)) > 0)
     {

       ms.Write(buffer,0,read);

     }

return ms.ToArray();

}

}



and in Configration use webHttpbinding change the maxReceivedMessageSize.

<webHttpBinding>
<binding name="webHttpBindingStreamed" transferMode="StreamedRequest" maxReceivedMessageSize="2147483647">
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
</binding>
</webHttpBinding>

the max length for Receive buffer is 2147483647, also add the readerQuotas.
may be this will help you.

2 comments:

  1. i use your webhttp binding but i can upload 65kb only. if i uploaded more than 65 kb then i get 400 error . i didn't hosting service on iis

    ReplyDelete
    Replies
    1. You need to change in web.config file.
      change maxStringContentLength and maxReceivedMessageSize value then it should work.

      Delete