New to Telerik UI for ASP.NET AJAXStart a free 30-day trial

How to upload files from MAC or Linux

On some operating systems like MAC OS and Linux it is possible to have file names, which are invalid for the Windows File System, may contain special characters or might not be in accordance with the Microsoft's Naming Convention. This makes file uploading impossible. That's why to upload a file with such invalid name we have to rename it before the uploading. Due to the nature of AsyncUpload and due to security restrictions such renaming will require a special way of implementation.

Uploading files from MAC OS or Linux

ASPNET
<telerik:RadAsyncUpload RenderMode="Lightweight" ID="RadAsyncUpload1" runat="server" HttpHandlerUrl="~/CustomHandler.ashx"  Target="~/Uploads"></telerik:RadAsyncUpload>
<asp:Button ID="btnSubmit" runat="server" Text="Submit Uploaded Files" />
  • Override the ChageOriginalFileName method and perform own file name validation
C#
<%@ WebHandler Language="C#" Class="CustomHandler" %>

using System;
using System.Web;
using Telerik.Web.UI;
using System.Text.RegularExpressions;
using System.IO;

public class CustomHandler : AsyncUploadHandler
{
    protected override string ChangeOriginalFileName(string fileName)
    {
        return EscapeInvalidCharacter(fileName);
    }

    //Sample escaping of invalid windows characters
    private string EscapeInvalidCharacter(string fileName)
    {
        //Check if there is no invalid characters return the current name
        if (fileName.IndexOfAny(System.IO.Path.GetInvalidFileNameChars()) == -1)
        {
            return fileName;
        }
        else
        {
            //Escape invalid characters
            fileName = Regex.Replace(fileName, @"[^\w\.@-]", "", RegexOptions.None, TimeSpan.FromSeconds(1.5));
            //If all characters are invalid return underscore as a file name
            if (Path.GetFileNameWithoutExtension(fileName).Length == 0)
            {
                return fileName.Insert(0, "_");
            }
            //Else return the escaped name
            return fileName;
        }
    }
}

The solution above results in a red highlighting and no upload of the file, but it does not let the framework know that the filename changed is actually invalid. This extra check can be done like this:

C#
    protected override bool CheckOriginalFileNameForInvalidChars(string filename)
    {
        return isValid(filename) ... ;
    }

You can find more information at Custom File Name Validation.

See Also