IT researcher
IT researcher

Reputation: 3304

File upload is reset on submit button click

I am using upload feature in my asp website. So i am using file input type. But this control add a default upload button browse and a textbox where path is shown after selecting file in Internet explorer. I don't want to show browse button etc. So what i did is add a button "Attach a File" and i have written script 'triggerFileUpload' function where i make it to click on upload control. So now when i click on "Attach a File" button browse for file windows appears and can select file to upload. But when i click on submit button the file upload control becomes reset and file is not uploaded. Error is that on clicking to submit button the file control becomes null. It happens only in internet explorer. So please help me to solve this.Below is code which can show the problem i am facing in IE.Same problem comes if i use asp:FileUpload control also. (my plan is to hide the file control and show only attach file button to user).

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

<!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 runat="server">
    <title></title>
    <script type="text/javascript">
      function triggerFileUpload() {
          document.getElementById("FileUploaddd2").click();
      }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <input id="Button2" type="button" onclick="triggerFileUpload()" value="Attach a File" />
     <input type="file" id="FileUploaddd2" runat="Server" />
     <br />
    <asp:Button ID="btnSubmit" runat="server" BorderColor="Black" 
                            BorderStyle="Solid" BorderWidth="1px"
                            Text="Submit" />
    </div>
    </form>
</body>
</html>

Download the sample code here

UPDATE

To reproduce the error i am facing

1) run the project i have given in the download link

2) Test in Internet explorer-any version

3)Click on attach a file button (not on browse,it is intended to make visible false,here shown only for example purpose)

4)browse for files in windows appearing and click OK

5)now click on Save button.

When save button is clicked btnsave_Click function should trigger,but it is not triggering.If i click again on save button btnsave_Click gets triggered.But this time the upload control will not be having the file selected.you can see it in the textbox provided by browse control also(only for showing this i made browse control as visible)

So now question why btnsave_Click is not triggered for the first time?

Upvotes: 9

Views: 15750

Answers (4)

afzalulh
afzalulh

Reputation: 7943

Problem is IE wouldn't let you submit a file through javascript, user have to click the file input. It is a known problem, described here:

When an file-input is opened via a scripted, forced click() event, IE won't let you submit the form. If you click the file-input via your own mouse (what we don't want), IE will let you submit the form.Open file input dialog and upload onchange possible in IE?

and also here: File Upload Using Javascript returns 'Access Denied' Error With Stylized to a button

So, you have to trick the user, make the file-input transparent and place your button under the file-input. When user will click your button, they will click the file input instead.

With the css (probably you will need to tweak it) your markup should look like below:

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

<!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">
    <style type="text/css">
        .fileContainer {
            overflow: hidden;
            position: relative;
        }

        #FileUploaddd2 {
            position: relative;
            text-align: right;
            -moz-opacity: 0;
            filter: alpha(opacity: 0);
            opacity: 0;
            z-index: 2;
            left: -130px;
        }

        #Button2 {
            position: absolute;
            top: 0px;
            left: 0px;
            z-index: 1;
        }
    </style>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <label class="fileContainer">
                <input id="Button2" type="button" value="Attach a File" />
                <input type="file" id="FileUploaddd2" runat="Server" />
            </label>
            <br />
            <br />
            <asp:Button ID="btnSubmit" runat="server" BorderColor="Black"
                BorderStyle="Solid" BorderWidth="1px"
                Text="Submit" />
        </div>
    </form>
</body>
</html>

And in the code behind you can catch the submitted file

Protected Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
    Dim file As System.Web.HttpPostedFile = FileUploaddd2.PostedFile
    If Not file Is Nothing Then
        'Save file?
    End If
End Sub

EDIT: If you want to show the filename in a label, you can do the following:

In Input file's change event call a jsfunction:

<input type="file" id="FileUploaddd2" runat="Server" onchange="setlabelvalue();" />

Add a label to display filename:

<asp:Label ID="lblFileName" runat ="server" Text=""></asp:Label>

Add the setlabelvalue() js function:

function setlabelvalue() {
            var filename = document.getElementById("FileUploaddd2").value;
            var lastIndex = filename.lastIndexOf("\\");

            if (lastIndex >= 0) {
                filename = filename.substring(lastIndex + 1);
            }
            document.getElementById('<%=lblFileName.ClientID%>').innerHTML = filename;
        }

Upvotes: 6

Jean Carlos
Jean Carlos

Reputation: 51

i don't know if i misunderstood the question, but why don't you do:

triggerFileUpload() {
      document.forms[0].submit();
}

Upvotes: 1

Naveed Butt
Naveed Butt

Reputation: 2901

Are you sure that the click is working ? Because I think you are not writing the java script code correctly.

You need to get the ClientID of the file upload in java script

like this:

document.getElementById('<%=  FileUploaddd2.ClientID %>').click();

After your Update, I was able to run the code successfully...

I think you need to add this line after the try catch block inside the if block in your server side code...

    Try
        sb.AppendFormat(" Uploading file: {0}", FileUpload1.FileName)
        'saving the file
        FileUpload1.SaveAs("c:\SaveDirectory\" + FileUpload1.FileName)
        'Showing the file information
        sb.AppendFormat("<br/> Save As: {0}", FileUpload1.PostedFile.FileName)
        sb.AppendFormat("<br/> File type: {0}", FileUpload1.PostedFile.ContentType)
        sb.AppendFormat("<br/> File length: {0}", FileUpload1.PostedFile.ContentLength)
        sb.AppendFormat("<br/> File name: {0}", FileUpload1.PostedFile.FileName)
    Catch ex As Exception
        sb.Append("<br/> Error <br/>")
        sb.AppendFormat("Unable to save file <br/> {0}", ex.Message)
    End Try
    lblmessage.Text = sb.ToString()

AFTER UPDATE

After seeing the update regarding the Internet Explorer. I think your problem is this:

Simulating the click on input type="file" using javascript

This might also help: Browser check before executing an event

You can also use Ajax Control Toolkit's AjaxFileUpload for better display and features like drag and drop are already implemented in that: Have a look. This way you won't have to simulate a click on the button.

Upvotes: 1

Prashant Lakhlani
Prashant Lakhlani

Reputation: 5806

File upload in asp.net is pretty straight forward but requires some tweaks. Here is the example:

<form id="Form1" method="post" runat="server" enctype="multipart/form-data">
<input id="filMyFile" type="file" runat="server"><br/>
<asp:Button ID="btnSubmit" runat="server" BorderColor="Black" 
                            BorderStyle="Solid" BorderWidth="1px"
                            Text="Submit" />
</form>

Try this and it should work.

Once you upload file, you have make filMyFile.Visible=false; and add label to show uploaded file and link button to remove it.

I hope that makes sense now.

Here is a really straight forward reference: http://www.codeproject.com/Articles/1757/File-Upload-with-ASP-NET

Upvotes: 1

Related Questions