Home / Community & Support / Knowledge Base / RadControls for Silverlight / Upload / Saving files with unique name on the server using RadUploadHandler

Saving files with unique name on the server using RadUploadHandler

Article Info

Rating: 5

Article information

Article relates to

 RadUpload

Created by

 Kiril Stanoev

Last modified

 03.01.2011

Last modified by

 Tina Stancheva


This article will demonstrate how to use RadUpload and save files under unique name on the server.
The article can be divided into 4 main parts:
  1. Create and set up Silverlight web project
  2. Use the ChunkTag mechanism to set unique name to the file
  3. Use the GetAssociatedData() method where the new unique file name is sent back to the client upload control
  4. Display the new file name

Let's start by creating a new Silverlight project and naming it RadUploadDemo.
Note: Make sure you host the Silverlight application in an ASP.NET Web Application project.



Open the Silverlight project (RadUploadDemo) and add references to Telerik.Windows.Controls.dll and Telerik.Windows.Controls.Input.dll.
After that add an instance of RadUpload in MainPage.xaml.

<telerik:RadUpload 
    x:Name="radUpload" 
    Filter="All Files(*.*)|*.*" 
    FilterIndex="3" 
    IsAutomaticUpload="False" 
    OverwriteExistingFiles="True" 
    UploadServiceUrl="../RadUploadHandler.ashx" 
    TargetFolder="MyStorageFolder" 
    FileUploaded="radUpload_FileUploaded" 
    > 
</telerikInput:RadUpload> 

Note: In this demo, RadUpload uses a custom template for its items. The full definition of RadUpload can be found in the attached file. For the moment, all you have to know is that RadUpload will display the new file name (how the file is named on the server) inside a TextBlock with x:Name="NewFileName". This TextBlock is located in RadUpload's ItemContainerStyle.

Most of the properties and events of RadUpload are pretty self-explanatory. The ones that deserve more attention are UploadServiceUrl, FileUploaded and TargetFolder.
The UploadServiceUrl just points to the handler that receives and saves the uploaded files on the server. The TargetFolder sets the folder that will contain the uploaded files on the server, but more on this later. For the moment, let's focus on what happens when a file gets uploaded. The FileUploaded event fires every time a file has been uploaded on the server. The FileUploadedEventArgs has a property called HandlerData. HandlerData, on its side, has a Dictionary property called CustomData, that allows to store and send data from the server to the client. Later you will see how to send custom data from the server.
So, in the radUpload_FileUploaded event handler, we have to find the TextBlock with x:Name="NewFileName" (see note above) and set its Text property to the new file name, which is obtained from the CustomData property.
private void radUpload_FileUploaded(object sender, FileUploadedEventArgs e)
{
    RadUploadSelectedFile uploadedFile = e.SelectedFile;
    // CustomData is a Dictionary property that stores the new file name in value of a key.
    // This key is set in the RadUploadHandler.ashx.cs
    string newFileName = e.HandlerData.CustomData["NewFileName"].ToString();
 
    if (this.radUpload.CurrentSession.FileNameUploadItem.ContainsKey(uploadedFile.Name))
    {
        RadUploadItem item = this.radUpload.CurrentSession.FileNameUploadItem[uploadedFile.Name];
        if (item != null)
        {
            // Retrieve the TextBlock that will hold new file name
            FrameworkElement element = GetCustomTagControl(item, "NewFileName");
            if (element != null)
            {
                TextBlock textBlock = element as TextBlock;
                if (textBlock != null)
                {
                    textBlock.Text = newFileName;
                    textBlock.Visibility = Visibility.Visible;
                }
            }
        }
    }
}
 
private static FrameworkElement GetCustomTagControl(DependencyObject control, string name)
{
    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(control); i++)
    {
        DependencyObject child = VisualTreeHelper.GetChild(control, i);
        FrameworkElement element = child as FrameworkElement;
 
        if (element != null)
        {
            if (0 == string.Compare(element.Name, name, StringComparison.InvariantCultureIgnoreCase))
            {
                return element;
            }
        }
        element = GetCustomTagControl(child, name);
        if (element != null)
        {
            return element;
        }
    }
    return null;
}

Enough with the client. It is time to see what happens on the server.
Open the RadUploadDemo.Web project and add a reference to the Telerik.Windows.RadUploadHandler.dll. After that, right-click on RadUploadDemo.Web and select Add > New Item. Add a Generic Handler and call it RadUploadHandler.ashx. Also add a New Folder and call it MyStorageFolder.



Open the RadUploadHandler.ashx file. Your handler(int this case RadUploadHandler) has to inherit Telerik.Windows.RadUploadHandler and override few important methods.
public class MyUploadHandler : Telerik.Windows.RadUploadHandler
{
    public override Dictionary<string, object> GetAssociatedData()
    {
 
    }
 
    public override string GetFilePath(string fileName)
    {
 
    }
 
}

The GetFilePath method gets invoked internally and returns the absolute path of the file. Therefore, if we want to save the file under different name, we will have to override this method.
The next method is GetAssociatedData. This method gets invoked after the last portion of the file has been uploaded. In this method we have the chance to insert any data we want, and this data will be transfered back to the client.
public class MyUploadHandler : Telerik.Windows.RadUploadHandler
{
    private string newFileName = string.Empty;
 
    public override Dictionary<string, object> GetAssociatedData()
    {
        Dictionary<string, object> dict = base.GetAssociatedData();
        if (!string.IsNullOrEmpty(newFileName))
        {
            dict.Add("NewFileName", this.newFileName);
        }
        return dict;
    }
 
    public override string GetFilePath(string fileName)
    {
        fileName = base.GetFilePath(this.GetFileName(fileName));
        return fileName;
    }
 
    private string GetFileName(string fileName)
    {
        if (this.IsNewFileRequest())
        {
            this.ResultChunkTag = string.Format(" [{0:yyyymmdd_hhmmss}]", DateTime.Now);
        }
 
        else if (this.FormChunkTag != null)
        {
            this.ResultChunkTag = this.FormChunkTag;
        }
 
        if (this.ResultChunkTag != null)
        {
            int i = fileName.LastIndexOf('.');
            if (i >= 0)
            {
                fileName = fileName.Insert(i, this.ResultChunkTag);
            }
        }
        return this.newFileName = fileName;
    }
}

More or less this is it. Now, let's test the project.



Hit the Browse button, and select files you wish to upload.





Click Upload and files will be sent on the server.
As soon as the upload finishes, you will see the server names of the files.



Finally you can find the files uploaded in the MyStoreFolder folder.




Comments

If you'd like to comment on this KB article, please, send us a Support Ticket.
Thank you!

Please Sign In to rate this article.