Validate uploaded file extension using AjaxFileUpload and change file name in ASP.Net

Last Reply one year ago By pandeyism

Posted one year ago

hello,

i have ajax file upload control it works fine

  <asp:AjaxFileUpload ID="AjaxFileUpload11" runat="server" MaximumNumberOfFiles="5"
    Width="400px" OnUploadComplete="OnUploadComplete"   />

 

    protected void OnUploadComplete(object sender, AjaxFileUploadEventArgs e)
    {        
          string  fileName = Path.GetFileName(e.FileName);
          AjaxFileUpload11.SaveAs(Server.MapPath("~/upload/" + fileName));
    }

i want to apply this condition ext of file check before upload file and also change the file name to guid + ext so it always unique and do not mix up with same file name

string ext = Path.GetExtension(FileUpload1.FileName).ToLower(); 
if (ext == ".jpg" || ext == ".jpeg" || ext == ".gif" || ext == ".png") 
{ 
    uploadFileName = Guid.NewGuid().ToString() + ext;
}

i know how to do it withe asp file upload control but with ajax it does not work

please advice thanks

Posted one year ago

Hi nauna,

Please refer below sample.

HTML

<asp:ToolkitScriptManager runat="server">
</asp:ToolkitScriptManager>
<asp:AjaxFileUpload ID="AjaxFileUpload11" runat="server" MaximumNumberOfFiles="5"
    Width="400px" OnUploadComplete="OnUploadComplete" />

Namespaces

C#

using System.IO;
using AjaxControlToolkit;

Vb.Net

Imports System.IO
Imports AjaxControlToolkit

Code

C#

protected void OnUploadComplete(object sender, AjaxFileUploadEventArgs e)
{
    string fileName = Path.GetFileName(e.FileName);
    string ext = Path.GetExtension(e.FileName);
    if (ext == ".jpg" || ext == ".jpeg" || ext == ".gif" || ext == ".png")
    {
        fileName = Guid.NewGuid().ToString() + ext;
    }
    AjaxFileUpload11.SaveAs(Server.MapPath("~/Uploads/" + fileName));
}

VB.Net

Protected Sub OnUploadComplete(ByVal sender As Object, ByVal e As AjaxFileUploadEventArgs)
    Dim fileName As String = Path.GetFileName(e.FileName)
    Dim ext As String = Path.GetExtension(e.FileName)
    If ext = ".jpg" OrElse ext = ".jpeg" OrElse ext = ".gif" OrElse ext = ".png" Then
        fileName = Guid.NewGuid().ToString() & ext
    End If
    AjaxFileUpload11.SaveAs(Server.MapPath("~/Uploads/" & fileName))
End Sub