Monday, 27 August 2012

How to upload big file in Silverlight using WCF?

I am recently trying to upload some big files(100MB or 1GB) to server using WCF in Silverlight Client, but found it is a really tough work. So I googled for few hours and found some SEEMED helpful result, I say SEEMED means NONE of them works perfectly, NONE, all of these result has at least one problems I listed below:


  1. Doesn't work at all, either from Silverlight side or from server side
  2. Works, the result is good, but from Silverlight side, the whole file is read into the memory by using a big buffer byte[], which cause an Out of  Memory Exception in uploading period
  3. Works, from the Silverlight side, the big file is split into some small package and transfer to the server piece by piece. everything is OK, looks beautiful, but the only problem is, the FILE which was uploaded to the server is forever DAMAGED.  the bytes are the same, but the content of the file is changed which makes the upload useless.
If you can find any other solution other than mine which can do a real successful upload, please let me know.

OK, let's process on, let me teach you how to built a solution to upload a 100MB file from Silverlight side to WCF server.




  • WCF Server Side
    • On server side, create a Console Application, add these references
      System.ServiceModel
    • Add an interface called IMatt   ====>









      Don't worry about GetName() and UploadFile2(), we don't use them here, it's for testing other stuff
    • Create a class inherit the interface, we only care about two methodes
      UploadFileInfo(string fileInfo) and UploadFile(Stream sr);
    • Here you can see we transfer file by using a Stream, not byte[], which means we are using
      transferMode="StreamedResponse" to transfer files, by default, WCF will use transferMode="buffer", we have to changed this parameter in the web.config file to be "StreamedResponse"
    • Before transferring, I have to tell the service the file's detail information, because I will have to split the file into small pieces and transfer to the server piece by piece, by receiving all the pieces, I merge them into one integral file, thus, I don't have to read a big file all into memory which might cause "Out of memory exception"
      UploadFileInfo method is to tell the service the file's information, and the service has to calculate some parameters which will be used later 
    •  After the  UploadFileInfo is run, than started UploadFile(Stream sr)
      this will be invoked a number of times, depending on how big the file is and how big the buffer is




    

No comments:

Post a Comment