Community Pick: Many members of our community have endorsed this article.

File Upload In silverlight using Web service (.asmx)

Published:
Updated:
In My Article File Handling in Silverlight I have discussed that we can use file upload using the Isolated storage of Silverlight. We also have another way using the classic (.asmx) Web services or WCF.

Here I am discussing about the classic .asmx web services to upload files in the Silverlight applications.

Steps :


1.  Create a Silverlight project in Visual Studio 2008 or beyond. As Silverlight 3.0 is released so you can use that or go with Silverlight 2.0 hardly matters.

2.  Make these important changes in the properties of FileUploadASMX.Web project
     a.  Right click on FileUploadASMX.Web.
     b.  Select Properties
     c.  Under Web tab Select Specific port and give the port number I am using port number 1366 Note: we are using specific port so that every time we need not to run the web service to use it and it won't change its address. If you don't want to use specific port then either host your web service on IIS or run the web service every time and update the service reference each time before running the application.
     d.  Save The Properties Page and close it.

3.  Add a new Web service to the FileUploadASMX.Web project and name it as uploadService.asmx

4.  Include the name space  System.IO
using System.IO;

Open in new window


5.  Create a new web method
//method for upload the files. This will be called from Silverlight code behind.
                      [WebMethod]
                      public string UploadFiles(string strFileName, byte[] byFile, string strFileNo)
                      {
                          try
                          {
                              if (byFile.Length > 0)
                              {
                                  string strFilePath = "D:\\meet\\" + strFileName;
                                  System.IO.FileStream fs = new FileStream(strFilePath, FileMode.Create, FileAccess.Write);
                                  fs.Write(byFile, 0, byFile.Length);
                                  fs.Close();
                                  return strFileNo;
                              }
                              else
                              {
                                  return "";
                              }
                          }
                          catch
                          {
                              return "";
                          }
                      } 

Open in new window


6.  Save the Service Leaving other settings as it is. or you want then you can delete the Helloworld example web method.

7.  Coming back to the FileUploadASMX project.

8.  Create A class FilesClass
public class FilesClass
                      {
                          public FilesClass()
                          {
                              //do nothing
                          }
                          string strStatus = "";
                          string strNo = "";
                          FileInfo strFileName = null;
                          public string PropNumber
                          {
                              get
                              {
                                  return strNo;
                              }
                              set
                              {
                                  strNo = value;
                              }
                          }
                          public FileInfo PropFileName
                          {
                              get
                              {
                                  return strFileName;
                              }
                              set
                              {
                                  strFileName = value;
                              }
                          }
                          public string PropStatus
                          {
                              get
                              {
                                  return strStatus;
                              }
                              set
                              {
                                  strStatus = value;
                              }
                          }
                      }

Open in new window


9.  Create Two Buttons in the Mainpage.xaml.
     a.  To Choose File
     b.  To upload File At the specified folder in the Web Service

The Code Will look like
<Grid x:Name="LayoutRoot" Background="White" Width="400" Height="50"> 
                      <Button Content="Choose" Height="20" Width="150" Click="Button_Click" Margin="10,0,10,10" VerticalAlignment="Bottom" d:LayoutOverrides="Width, Height" HorizontalAlignment="Left" Background="#FF2770AF"></Button> 
                      <Button Content="Upload" Height="20" Width="150" Click="Button_Click_1" Margin="20,0,10,10" VerticalAlignment="Bottom" d:LayoutOverrides="Width, Height" HorizontalAlignment="Right" Background="#FF2770AF"></Button> 
                      </Grid>

Open in new window


10.  Add the service reference to the Silverlight project name it  uploadService

11.  Navigating to the event for choose button
private void Button_Click(object sender, RoutedEventArgs e)
                      {
                          //create an oblect for file open dialog
                          OpenFileDialog op = new OpenFileDialog();
                          //show the file browser dialog to select file
                          op.ShowDialog();
                          //if any file is selected
                          if (op.File != null && op.File.Name != "")
                          {
                              //check the file size. It should be less than 1MB
                              if (op.File.Length < 1048576)
                              {
                                  //create a new fill class object to maintain the file content
                                  FilesClass obj = new FilesClass();
                                  //assign file
                                  obj.PropFileName = op.File;
                                  //passing file number
                                  obj.PropNumber = iFileCount.ToString();
                                  //add the file object to files list collection
                                  fl.Add(obj);
                                  iFileCount++;
                              }
                              //IF size is greater than 1 MB show the message
                              else
                              {
                                  MessageBox.Show("Max file size is 1 MB");
                              }
                          }
                          //display message to the user if no file is selected
                          else
                          {
                              MessageBox.Show("Select File");
                          }
                      }

Open in new window


12.  Now Lets code for the upload event Navigate to the event
private void Button_Click_1(object sender, RoutedEventArgs e)
                      {
                          if (fl.Count > 0)
                          {
                              //loop through the files and upload the files by passing it to web service.
                              for (int count = 0; count < fl.Count; count++)
                              {
                                  uploadService.uploadServiceSoapClient x = new uploadService.uploadServiceSoapClient();
                                  //here is the event handler, which will be invoked for every file upload
                                  x.UploadFilesCompleted += new EventHandler<uploadService.UploadFilesCompletedEventArgs>(UploadFileComplted);
                                  //read the file from file class
                                  FilesClass obj = (FilesClass)fl[count];
                                  System.IO.FileStream str = obj.PropFileName.OpenRead();
                                  byte[] by = new byte[str.Length];
                                  str.Read(by, 0, by.Length);
                                  str.Close();
                                  //call the upload file methods async event, which will upload the files asynchronously
                                  x.UploadFilesAsync(obj.PropFileName.Name, by, obj.PropNumber);
                              }
                          }
                      }
                      private void UploadFileComplted(object sender, uploadService.UploadFilesCompletedEventArgs e)
                      {
                          if (e.Result != "")
                          {
                              MessageBox.Show("File Uploaded");
                          }
                      }

Open in new window


The Code Is Attached you can Download the files and enjoy file handling


--------------------------------------------------------------------------------
Thanks and Regards
Meetu Choudhary
MVP.
My Blog || My Web || My Forums
3
9,241 Views

Comments (0)

Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.