Use ASP.Net Button as FileUpload control using C# and VB.Net

ashish007
 
on Apr 11, 2021 12:57 PM
2857 Views

How to use Button as FileUpload control in ASP.Net

I have click the upload and open file dialogue box show and select image file, but file not upload debug this code error find pls select a file.

fileupload control not select in file.

<asp:Content ID="Content1" ContentPlaceHolderID="head11" runat="Server">

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
    $(function () {
        $("[id*=Button1]").click(function () {
            $(this).closest('tr').find("[id*=FileUpload1]").click();
        });
    });
</script>
    
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
    <table  class="style7">
        <tr>
            <td>
         
                <asp:Label ID="Label1" runat="server" Text="Label" Visible="false"></asp:Label>
            </td>
        </tr>
        <tr>
            <td>
                <table class="style14">
                    
                    <tr>
                        <td valign="bottom" style="padding-top: 10px;">
                            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                            <asp:FileUpload ID="FileUpload1" runat="server"  style="display:none;"  />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                            <asp:Button ID="Button1" Text="Upload" runat="server" OnClick="Upload" CssClass="btnpost" Height="300PX" />
                         </td>
                    </tr>
                </table>
                &nbsp;<font size="2">Share your good thoughts to your world.</font>
            </td>
        </tr>
    </table>
</asp:Content>

 

private void Insert_photo()
{
    try
    {
        if (FileUpload1.HasFile)
        {
 
            Label1.Visible = false;
            if (FileUpload1.FileName.ToUpper().EndsWith(".JPG") || FileUpload1.FileName.ToUpper().EndsWith(".GIF") || FileUpload1.FileName.ToUpper().EndsWith(".BMP") || FileUpload1.FileName.ToUpper().EndsWith(".PNG") || FileUpload1.FileName.ToUpper().EndsWith(".JPEG"))
            {
                Int32 lengh = FileUpload1.PostedFile.ContentLength;
                decimal size = Math.Round(((decimal)FileUpload1.PostedFile.ContentLength / (decimal)1024 / (decimal)1024), 2);
                if (size >= 5)
                {
                    Label1.Visible = true;
                    Label1.Text = "Invalid File size" + "." + "Max File Size 5MB";
                }
                else
                {
                    string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
                    FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Story/" + FileName));
                    link = "~/Story/" + FileName;
 
                    IP.insertstory(FileName, Int32.Parse(Session["uid"].ToString()), System.DateTime.Now.ToString(), link, "");
                    show_story();
                }
            }
            else if (FileUpload1.FileName.ToUpper().EndsWith(".WEBM") || FileUpload1.FileName.ToUpper().EndsWith(".MPG") || FileUpload1.FileName.ToUpper().EndsWith(".MP2") || FileUpload1.FileName.ToUpper().EndsWith(".MPEG") || FileUpload1.FileName.ToUpper().EndsWith(".MPE") || FileUpload1.FileName.ToUpper().EndsWith(".MPV") || FileUpload1.FileName.ToUpper().EndsWith(".OGG") || FileUpload1.FileName.ToUpper().EndsWith(".MP4") || FileUpload1.FileName.ToUpper().EndsWith(".M4V") || FileUpload1.FileName.ToUpper().EndsWith(".AVI") || FileUpload1.FileName.ToUpper().EndsWith(".WMV") || FileUpload1.FileName.ToUpper().EndsWith(".MOV") || FileUpload1.FileName.ToUpper().EndsWith(".QT") || FileUpload1.FileName.ToUpper().EndsWith(".FLV") || FileUpload1.FileName.ToUpper().EndsWith(".SWF"))
            {
                string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
                FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Story/" + FileName));
                link = "~/Story/" + FileName;
 
                IP.insertstory(FileName, Int32.Parse(Session["uid"].ToString()), System.DateTime.Now.ToString(), link, "");
                show_story();
            }
            else
            {
                Label1.Visible = true;
                Label1.Text = "Invalid File Extension";
            }
        }
        else
        {
            Label1.Visible = true;
            Label1.Text = "Pls Select File";
        }
    }
    catch (Exception ex)
    {
        Label1.Visible = true;
        Label1.Text = ex.Message;
    }
}

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
Adnaan
 
on Apr 12, 2021 04:28 AM

Hi ashish007,

You need another Button control and set its display none. Then assign change event to fileupload control. On selection of file trigger the serverside click event to save the record.

Also there might be a missing of story folder that is the reason you must be getting error.

Before you need to check if folder exist or not. If not exists the create folder.

Refer below updated code.

HTML

<table class="style7">
    <tr>
        <td></td>
    </tr>
    <tr>
        <td>
            <asp:Label ID="Label1" runat="server" Text="Label" Visible="false"></asp:Label>
        </td>
    </tr>
    <tr>
        <td>
            <table class="style14">
                FileUpload1
            <tr>
                <td valign="bottom" style="padding-top: 10px;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    <asp:FileUpload ID="FileUpload1" runat="server" Style="display: none;" />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    <asp:Button ID="Button1" Text="Upload" runat="server" CssClass="btnpost" Height="300PX" />
                    <asp:Button ID="btnSave" Text="Save" runat="server" Style="display: none;" OnClick="Upload" />
                </td>
                <td></td>
            </tr>
            </table>
            &nbsp;<font size="2">Share your good thoughts to your world.</font>
        </td>
    </tr>
    <tr>
        <td style="border-top-style: solid; border-top-width: thin; border-top-color: #808080">&nbsp;
        </td>
    </tr>
    <tr>
        <td>
            <div id="postt">
                <asp:DataList ID="Datalistpost" runat="server" Width="560px" BorderWidth="1px"
                RepeatLayout="Table">
                <ItemStyle CssClass="grid1" />
                <ItemTemplate>
                    <table style="width: 546px">
                        <tr>
                            <td style="width: 50px"></td>
                            <td class="style11">
                                <br />
                                <asp:Image ID="im11" runat="server" ImageUrl='<%#Eval("file_name") %>' Width="120px"
                                    Height="120px" /><br />
                            </td>
                        </tr>
                        <tr>
                            <td class="style11">&nbsp;
                            </td>
                            <td style="text-align: left;"></td>
                        </tr>
                        <tr>
                            <td class="style11">&nbsp;
                            </td>
                            <td style="text-align: left"></td>
                        </tr>
                        <tr>
                            <td colspan="2"></td>
                        </tr>
                    </table>
                </ItemTemplate>
            </asp:DataList>
            </div>
            <asp:Label ID="lblerr" runat="server" CssClass="errmsg"></asp:Label>
        </td>
    </tr>
    <tr>
        <td></td>
    </tr>
</table>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
    $(function () {
        $("[id*=Button1]").click(function () {
            $(this).closest('tr').find("[id*=FileUpload1]").click();
            return false;
        });

        $("[id*=FileUpload1]").on('change', function () {
            $("[id*=btnSave]")[0].click();
        });
    });
</script>

Code

C#

protected void Upload(object sender, EventArgs e)
{
    Insert_photo();
}

private void Insert_photo()
{
    string link = "";
    try
    {
        if (FileUpload1.HasFile)
        {
            Label1.Visible = false;
            if (!Directory.Exists(Server.MapPath("~/Story/")))
            {
                Directory.CreateDirectory(Server.MapPath("~/Story/"));
            }

            string extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
            string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
            link = "~/Story/" + FileName;
            if (extension.ToUpper().EndsWith(".JPG") || extension.ToUpper().EndsWith(".GIF") || extension.ToUpper().EndsWith(".BMP") || extension.ToUpper().EndsWith(".PNG") || extension.ToUpper().EndsWith(".JPEG"))
            {
                Int32 lengh = FileUpload1.PostedFile.ContentLength;
                decimal size = Math.Round(((decimal)FileUpload1.PostedFile.ContentLength / (decimal)1024 / (decimal)1024), 2);
                if (size >= 5)
                {
                    Label1.Visible = true;
                    Label1.Text = "Invalid File size" + "." + "Max File Size 5MB";
                }
                else
                {
                    FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Story/") + FileName);
                    IP.insertstory(FileName, Int32.Parse(Session["uid"].ToString()), System.DateTime.Now.ToString(), link, "");
                    show_story();
                }
            }
            else if (extension.ToUpper().EndsWith(".WEBM") || extension.ToUpper().EndsWith(".MPG") || extension.ToUpper().EndsWith(".MP2") || extension.ToUpper().EndsWith(".MPEG") || extension.ToUpper().EndsWith(".MPE") || extension.ToUpper().EndsWith(".MPV") || extension.ToUpper().EndsWith(".OGG") || extension.ToUpper().EndsWith(".MP4") || extension.ToUpper().EndsWith(".M4V") || extension.ToUpper().EndsWith(".AVI") || extension.ToUpper().EndsWith(".WMV") || extension.ToUpper().EndsWith(".MOV") || extension.ToUpper().EndsWith(".QT") || extension.ToUpper().EndsWith(".FLV") || extension.ToUpper().EndsWith(".SWF"))
            {
                FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Story/") + FileName);
                IP.insertstory(FileName, Int32.Parse(Session["uid"].ToString()), System.DateTime.Now.ToString(), link, "");
                show_story();
            }
            else
            {
                Label1.Visible = true;
                Label1.Text = "Invalid File Extension";
            }
        }
        else
        {
            Label1.Visible = true;
            Label1.Text = "Pls Select File";
        }
    }
    catch (Exception ex)
    {
        Label1.Visible = true;
        Label1.Text = ex.Message;
    }
}

VB.Net

Protected Sub Upload(ByVal sender As Object, ByVal e As EventArgs)
    Insert_photo()
End Sub

Private Sub Insert_photo()
    Dim link As String = ""
    Try
        If FileUpload1.HasFile Then
            Label1.Visible = False

            If Not Directory.Exists(Server.MapPath("~/Story/")) Then
                Directory.CreateDirectory(Server.MapPath("~/Story/"))
            End If

            Dim extension As String = Path.GetExtension(FileUpload1.PostedFile.FileName)
            Dim FileName As String = Path.GetFileName(FileUpload1.PostedFile.FileName)
            link = "~/Story/" & FileName

            If extension.ToUpper().EndsWith(".JPG") OrElse extension.ToUpper().EndsWith(".GIF") OrElse extension.ToUpper().EndsWith(".BMP") OrElse extension.ToUpper().EndsWith(".PNG") OrElse extension.ToUpper().EndsWith(".JPEG") Then
                Dim lengh As Int32 = FileUpload1.PostedFile.ContentLength
                Dim size As Decimal = Math.Round((CDec(FileUpload1.PostedFile.ContentLength) / CDec(1024) / CDec(1024)), 2)

                If size >= 5 Then
                    Label1.Visible = True
                    Label1.Text = "Invalid File size" & "." & "Max File Size 5MB"
                Else
                    FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Story/") & FileName)
                    IP.insertstory(FileName, Int32.Parse(Session("uid").ToString()), System.DateTime.Now.ToString(), link, "")
                    show_story()
                End If
            ElseIf extension.ToUpper().EndsWith(".WEBM") OrElse extension.ToUpper().EndsWith(".MPG") OrElse extension.ToUpper().EndsWith(".MP2") OrElse extension.ToUpper().EndsWith(".MPEG") OrElse extension.ToUpper().EndsWith(".MPE") OrElse extension.ToUpper().EndsWith(".MPV") OrElse extension.ToUpper().EndsWith(".OGG") OrElse extension.ToUpper().EndsWith(".MP4") OrElse extension.ToUpper().EndsWith(".M4V") OrElse extension.ToUpper().EndsWith(".AVI") OrElse extension.ToUpper().EndsWith(".WMV") OrElse extension.ToUpper().EndsWith(".MOV") OrElse extension.ToUpper().EndsWith(".QT") OrElse extension.ToUpper().EndsWith(".FLV") OrElse extension.ToUpper().EndsWith(".SWF") Then
                FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Story/") & FileName)
                IP.insertstory(FileName, Int32.Parse(Session("uid").ToString()), System.DateTime.Now.ToString(), link, "")
                show_story()
            Else
                Label1.Visible = True
                Label1.Text = "Invalid File Extension"
            End If
        Else
            Label1.Visible = True
            Label1.Text = "Pls Select File"
        End If

    Catch ex As Exception
        Label1.Visible = True
        Label1.Text = ex.Message
    End Try
End Sub