Tuesday, October 15, 2013

Upload a file using Web Service

Upload a file using byte array :

Web service method:


  [WebMethod]
        public string UploadFile(byte[] f, string fileName)
        {
            // the byte array argument contains the content of the file and 
            //the string argument contains the name and extension
            try
            {
                MemoryStream ms = new MemoryStream(f);

                //open a file stream pointing the storage folder 'uFiles'

                FileStream fs = new FileStream(System.Web.Hosting.HostingEnvironment.MapPath
                            ("~/uFiles/") + fileName, FileMode.Create);

                // write the memory stream  to the filestream
                ms.WriteTo(fs);
               
                ms.Close();
                fs.Close();
                fs.Dispose();
                return "OK";
            }

            catch (Exception ex)
            {
                     return ex.Message.ToString();
            }
        }


Sample win application code which consumes the method.


 FileInfo fInfo = new FileInfo(<<path & filename>>);

 FileStream fStream = new FileStream(<<path & filename>>,FileMode.Open, FileAccess.Read);

 BinaryReader br = new BinaryReader(fStream);
                 
 // convert the file to a byte array
 byte[] data = br.ReadBytes((int) fInfo.Length);
 br.Close();

localhost.Service1 s = new localhost.Service1();

s.UploadFile(data, <<filename>>);

 fStream.Close();

fStream.Dispose();





No comments:

Post a Comment