/default.aspx
Silverlight .NET CMS and Controls
Home
/controls.aspx
Silverlight Controls
Controls
File Upload

Silverlight File Upload Component

This Silverlight File Upload component will help you build a UI with File Upload capability with the minimum amount of coding, the example we have on this page uses the Progress Bar control to give you a visual representation of the upload progress though as the File Upload is a separate component you can implement any UI you like for it.

How to Use the File Upload Component

To demonstrate the File Upload component we will build a simple upload page containing a Progress Bar and a file browse button, the browse dialog is a standard Silverlight dialog and allows the user to select 1 or many files. In your Silverlight XAML:

<UserControl x:Class="FileUpload.Page"
    xmlns="http://schemas.microsoft.com/client/2007"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:liquid="clr-namespace:Liquid;assembly=Liquid"
    Width="400" Height="300">
     <Canvas>
          <liquid:ProgressBar x:Name="progress" Canvas.Left="8" Canvas.Top="8" Width="200" Height="24" />
          <Button x:Name="startUpload" Canvas.Left="80" Canvas.Top="50" Content="Upload" Width="60" Height="32" Click="StartUpload_Click" />
     </Canvas>
</UserControl>

 

In your C# code behind file you will actually get to use the Upload component to upload the selected files and to maintain the progress bar with the upload progress.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Browser;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

using Liquid;
using Liquid.Components;

namespace FileUpload
{
     public partial class Page : UserControl
     {
          private Uploader _uploader = new Uploader("http://localhost/vectorlight/FileUploadService.asmx");

          public Page()
          {
               InitializeComponent();

               _uploader.UploadProgressChange += new UploadEventHandler(Uploader_UploadProgressChange);
               _uploader.UploadFinished += new UploadEventHandler(Uploader_UploadFinished);
          }

          private void Uploader_UploadFinished(object sender, UploadEventArgs e)
          {
               progress.Text = "Complete.";
               progress.Complete = e.Progress;
          }

          private void Uploader_UploadProgressChange(object sender, UploadEventArgs e)
          {
               progress.Text = "Uploading " + Math.Round(e.Progress) + "% (" + e.Text + ")";
               progress.Complete = e.Progress;
          }

          private void StartUpload_Click(object sender, RoutedEventArgs e)
          {
               OpenFileDialog dialog = new OpenFileDialog();

               dialog.Filter = "Image files (*.gif;*.jpg;*.png)|*.gif;*.jpg;*.png";
               dialog.Multiselect = true;

               if (dialog.ShowDialog() == true)
               {
                    _uploader.UploadFiles(dialog.SelectedFiles, "documents/", true);
               }
          }
     }
}

 

In the example above we are handling the button Click event to display the local file browse dialog. When the user selects a file(s) we pass the selected file list property to the File Upload component which does the rest of the work for you.

The method Uploader_UploadProgressChange is called each time a portion of a file has been uploaded, the portion sizes are specified in the File Upload component using the PacketSize property (the default is 32768 or 32KB).

Receiving the File on the Server

The File Upload component uses a web service to push the data over to the server and your receiving web server must have a web service in order to receive the data. Below is an example of typical web service that could handle this:

using System;
using System.Collections;
using System.IO;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;

// <summary>
// Summary description for FileUploadService
//summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class FileUploadService : System.Web.Services.WebService
{
     public FileUploadService()
     {
          //Uncomment the following line if using designed components
          //InitializeComponent();
     }

     [WebMethod]
     public string Upload(string mode, string path, string name, string filedata, bool overwrite)
     {
          string filename = string.Empty;

          try
          {
               filename = Server.MapPath("~") + @"\" + path.Replace("/", @"\") + name;

               if (mode == "new")
               {
                    if (File.Exists(filename) == true)
                    {
                         if (overwrite)
                         {
                              File.Delete(filename);
                         }
                         else
                         {
                              return "File Already Exists";
                         }
                    }

                    WriteFile(filename, Convert.FromBase64String(filedata), FileMode.Create);
               }
               else
               {
                    WriteFile(filename, Convert.FromBase64String(filedata), FileMode.Append);
               }
          }
          catch (Exception ex)
          {
               File.Delete(filename);
               return "File Write Error: " + ex.Message;
          }

          return "ok";
     }

     private void WriteFile(string filename, byte[] content, FileMode fileMode)
     {
          Stream target = null;
          BinaryWriter writer = null;

          try
          {
               target = File.Open(filename, fileMode);
               writer = new BinaryWriter(target);

               writer.Write(content);
          }
          catch (Exception ex)
          {
               throw new Exception("Could not write to file: " + filename + " - " + ex.Message);
          }
          finally
          {
               if (target != null)
               {
                    target.Close();
               }
               if (writer != null)
               {
                    writer.Close();
               }
          }
     }
}


 

Your Comments and Questions Answered

 You are not logged in. You need to login to post new messages, if you do not have a login you can register for free!

dan Aug, 02 2008 - 09:42

Hi,

Firstly what is the URL of your web service you are calling in your Silverlight application? And what is the URL of you web service when you successfully test it? Also, could you provide the Upload() web service method declaration?

 

oksi Aug, 01 2008 - 05:47

Hi,

got version 4.8.
Used code from this page, but this line _uploader.UploadFiles(dialog.SelectedFiles, "documents/", true);
never hits the web service.
WEb service is tested, it works fine.
Any idea?

thanks

 

dan Jul, 01 2008 - 16:07

To andreyk44:

Can you provide more details of the problem you are having, from what I understand you are calling a web service locally (localhost) and that is working fine but on another server it is failing? It may be a symptom of cross-domain calling which is restricted in Silverlight, see http://silverlight.net/forums/t/7448.aspx.

 

dan Jul, 01 2008 - 15:58

Hello,

Thanks fro pointing this out, we will update this soon, in Silverlight 2 BETA 2 web service call-backs run in a different thread to the main UI and therefore cannot access UI properties. The file upload demo has been updated for BETA 2 and you can also download the example project from this page.

 

taazaa Jul, 01 2008 - 15:40

Hi,
Has this been updated to Beta 2? I just tried it and the web service never seems to be invoked or returned.

Thanks for your help.

 

andreyk44 Jul, 01 2008 - 06:38

I get exception System.InvalidOperationException for both versions 4.6 and 4.7 :
"Request format is unrecognized for URL unexpectedly ending in '/Upload'."
It happens only when SV client runs remotely. The same application works fine on localhost.

 

dan Jun, 10 2008 - 05:07

Hi Paul,

We're updating this demo at the moment. Basically in BETA 2 the Uploaded event handlers are running under a different thread to the main UI which causes problems when trying to set UI element properties (such as progress.Text in the above example) from an event handler.

We'll try to get this updated soon!

 

Paul Fretter Jun, 09 2008 - 11:31

Anyone tried the file upload under Beta 2? For me it stalls, never returning from the web service call. It was working fine under Beta 1.

Thanks

 

dan May, 15 2008 - 00:02

Hello,

This page has appeared a few days early! Version 4.5 will be out by th 18th May to download along with the demo code.

 

esueno May, 14 2008 - 13:33

This is amazing demo. I tried to download the demo source but he link is dead.
Also I don't see the FileUpload control in 4.4. When will it be released?
Thanks
-sw

 
This page is 40.65KB and was generated by the SilverPages CMS in 0.046 seconds. Total impressions: 868.