Change (Rename) FileName of uploaded File when using AJAX AsyncFileUpload control in ASP.Net

Last Reply on Feb 18, 2015 12:02 PM By Azim

Posted on Feb 18, 2015 12:00 PM

Hi

I am using this link for ajax image upload.

http://www.aspsnippets.com/Articles/Display-image-after-upload-without-page-refresh-or-postback-using-ASP.Net-AsyncFileUpload-Control.aspx

I want when the image is uploaded, it's name changes.

In other words I want to change the name of image.

How can I do this?

Posted on Feb 18, 2015 12:02 PM

I am using TextBox to change the uploaded file name.

Please refer this code.

You need to type some name in TextBox before selecting the File.

HTML

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>AsyncFileUpload Example</title>
    <script type="text/javascript">
        function uploadStarted() {
            $get("imgDisplay").style.display = "none";
        }
        function uploadComplete(sender, args) {
            var imgDisplay = $get("imgDisplay");
            imgDisplay.src = "images/loader.gif";
            imgDisplay.style.cssText = "";
            var img = new Image();
            img.onload = function () {
                imgDisplay.style.cssText = "height:100px;width:100px";
                imgDisplay.src = img.src;
            };
            img.src = "<%=ResolveUrl(UploadFolderPath) %>"
             + document.getElementById("<%=txtImageName.ClientID %>").value
             + args.get_fileName().substring(args.get_fileName().lastIndexOf(".")); ;
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <asp:TextBox ID="txtImageName" runat="server" />
    <cc1:AsyncFileUpload OnClientUploadComplete="uploadComplete" runat="server" ID="AsyncFileUpload1"
        Width="400px" UploaderStyle="Modern" CompleteBackColor="White" UploadingBackColor="#CCFFFF"
        ThrobberID="imgLoader" OnUploadedComplete="FileUploadComplete" OnClientUploadStarted="uploadStarted" />
    <asp:Image ID="imgLoader" runat="server" ImageUrl="~/images/loader.gif" /><br />
    <br />
    <img id="imgDisplay" alt="" src="" style="display: none" />
    </form>
</body>
</html>

C#

protected string UploadFolderPath = "~/Uploads/";

protected void FileUploadComplete(object sender, EventArgs e)
{
    if (AsyncFileUpload1.HasFile && !string.IsNullOrEmpty(txtImageName.Text.Trim()))
    {
        string filename = txtImageName.Text.Trim() + System.IO.Path.GetExtension(AsyncFileUpload1.FileName);
        AsyncFileUpload1.SaveAs(Server.MapPath(this.UploadFolderPath) + filename);
    }
}