Upload a file using ASP.Net file upload control and WCF

Madhu.B.Rokkam
Posted by in WCF category on for Intermediate level | Points: 250 | Views : 74821 red flag
Rating: 5 out of 5  
 2 vote(s)

I came across a question last week on how we can upload a file using a WCF service, So thought of solving through an example.

Introduction

I came across a question last week on how we can upload a file on to third party server using a WCF service, So thought of solving that through an example. 

So In this example we will upload a pdf file using ASP.Net upload control and passing the details to the WCF and saving the file in the server.

Objective

So as discussed our objective is to upload a pdf file from a web application to a third party server using a WCF service.


Using the code

So lets start building our sample step wise.

Step 1: First of all we will build the web application that a user will use to upload a file using the asp.net upload control. So lets code our aspx page as shown below.



Step 2: Now on the code behind file we will write the code to upload the details on btnUpload_click, where we will first validate to restrict the file type to be pdf and size to a max of 40 MB.



So here we have made sure to validate the posted file size not to exceed 40 MB and and type to be pdf file.

Step 3: We can also do a validation using the custom validation control too as below



Step 4: So on button click we have called a method called upload which will help us call our wcf service and send the details to save it on the third party server.

protected bool Upload(HttpPostedFile file, long actualFileSize)
        {
            int filePosition = 0;
            int filePart = 16 * 1024; //Each hit 16 kb file to avoid any serialization issue when transfering  data across WCF

            //Create buffer size to send to service based on filepart size
            byte[] bufferData = new byte[filePart];

            //Set the posted file data to file stream.
            Stream fileStream = file.InputStream;

            //Create the service client
            FUWcfService.FileUploadServiceClient serviceClient = new FUWcfService.FileUploadServiceClient();

            try
            {
                long actualFileSizeToUpload = actualFileSize;
                //Start reading the file from the specified position.
                fileStream.Position = filePosition;
                int fileBytesRead = 0;

                //Upload file data in parts until filePosition reaches the actual file end or size.
                while (filePosition != actualFileSizeToUpload)
                {
                    // read the next file part i.e. another 100 kb of data 
                    fileBytesRead = fileStream.Read(bufferData, 0, filePart);
                    if (fileBytesRead != bufferData.Length)
                    {
                        filePart = fileBytesRead;
                        byte[] bufferedDataToWrite = new byte[fileBytesRead];
                        //Copy the buffered data into bufferedDataToWrite
                        Array.Copy(bufferData, bufferedDataToWrite, fileBytesRead);
                        bufferData = bufferedDataToWrite;
                    }

                    //Populate the data contract to send it to the service method
                    bool fileDataWritten = serviceClient.UploadFileData(
                        new FUWcfService.FileData { FileName = file.FileName, BufferData = bufferData, FilePosition = filePosition });
                    if (!fileDataWritten)
                    {
                        break;
                    }

                    //Update the filePosition position to continue reading data from that position back to server
                    filePosition += fileBytesRead;
                }
            }
            catch (FaultException fex)
            {
                //Log data to database or file system here
                return false;
            }
            finally
            {
                //Close the fileStream once all done.
                fileStream.Close();
            }
            return true;
        }


Step 5: Next configure the web.config file to set the httpRuntime tag to set the maxRequestLength otherwise we will not be able to upload a big file like 40 MB file.

Also the WCF service details that we are going to create next.


Step 6: Now lets start creating the WCF service too from our side. First lets have the data contract and the interface.



Here we have created an interface IFileUploadService and the data contracts.

Step 7: Now the implementation part of the interface



Step 8: Finally lets configure the service 




Step 9: So Now its time to test our sample. Run the sample and the service.

So we have selected a pdf file and on clicking the upload button the file gets uploaded and the data is sent to the server through the WCF service part by part [16kb with each hit] and is saved in the server.



And finally displays the success message with the size of the file that got uploaded.

Hope you all will like it. And this would help all.


Conclusion

So we saw how easily we can upload a file across a wcf service. Let me know if you need any other details on this regard.

Page copy protected against web site content infringement by Copyscape

About the Author

Madhu.B.Rokkam
Full Name: Madhu Rokkam
Member Level: Bronze
Member Status: Member,MVP
Member Since: 1/13/2011 3:13:20 PM
Country: India
Thanks and Regards Madhu
http://www.dotnetfunda.com

Login to vote for this post.

Comments or Responses

Posted by: Karaniscool on: 10/25/2012 | Points: 25
Hi Madhu,

Can you make this example as Async?

Also f any exception occurs in the middle of the process, how can we delete the incomplete file ?

Thx,
Karan
Posted by: Akiii on: 10/27/2012 | Points: 25
Nice article..


Thanks and Regards
Akiii
Posted by: Rkrishnsaini on: 11/9/2012 | Points: 25
I tried this example. this is good when we are uploading any document like excel, pdf.. but when i tried to upload .jpg file then file goes blur and some time file not displaying and currepted. Can you help me to resolve this??

-Ramkrishn Saini
Posted by: Hernancano on: 4/14/2014 | Points: 25
Hello, thanks for your article.

I just want to comment that I had to add a "result = true;" line to the UploadFileData method on the WCF side because it always returned false and only uploaded the first 16KB of any file used to upload.

Again thank you for the information.

HC
Posted by: Bhupentiwari on: 5/10/2016 | Points: 25
Hi...Thanks for such a nice article.

Can u please send me the code on bhupentiwari[at]live.com

Login to post response

Comment using Facebook(Author doesn't get notification)