File upload is reset on submit button click

14,422

Solution 1

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;
        }

Solution 2

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.

Solution 3

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

Solution 4

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

triggerFileUpload() {
      document.forms[0].submit();
}
Share:
14,422
IT researcher
Author by

IT researcher

Updated on July 25, 2022

Comments

  • IT researcher
    IT researcher almost 2 years

    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?

  • IT researcher
    IT researcher over 10 years
    it's not working for me.problem still persists as before. What is clientID actually?
  • IT researcher
    IT researcher over 10 years
    Hey what you have mentioned is simple upload function.But i want upload control not at all visible to user.He will see only attch file button.On clicking it browse window will appear.
  • Naveed Butt
    Naveed Butt over 10 years
    What exactly do you mean by reset? How is the button get reset? Does the FileUpload control not return a value in the PostedFile?
  • IT researcher
    IT researcher over 10 years
    The upload file control is reset. The file selected will get empty. If you run the code given by me you will get exactly what i mean.
  • Naveed Butt
    Naveed Butt over 10 years
    I think you need to add an onclick event for the submit button, and in the code behind of the file for the event you need to get the file using FileUploaddd2.PostedFile.SaveAs()
  • IT researcher
    IT researcher over 10 years
    See my updated question.At the end i have added a download link for my code
  • IT researcher
    IT researcher over 10 years
    Have u tested it practically in Internet explorer? Whether file uploaded to C:\SaveDirectory folder? Also upload file by using "attach a file" button and then click on save.i tried it and it does not work in any of IE versions.(but works in chrome)
  • afzalulh
    afzalulh over 10 years
    @Naveed Butt- in which version of IE your code worked? Also, the OP is not using a masterpage or content for the FileUploaddd2, there's no point using clientID.
  • Naveed Butt
    Naveed Butt over 10 years
    @afzalulh I never said it worked on IE. It worked on Chrome. Plus ClientID is not related to master page, whenever there is nesting of server side controls, you have to use ClientID in javascript, because .Net renders the controls' IDs in a different way.
  • afzalulh
    afzalulh over 10 years
    OP clearly mentioned his code is working in all other browsers, only failing in IE. Your idea about ClientID is also wrong. Please check here in MSDN to be sure that OP doesnot need ClientID for the code he posted.
  • Naveed Butt
    Naveed Butt over 10 years
    @afzalulh This is not the place to get involved in that discussion. If you have some confusion regarding ClientID. Please open a question. I will try and answer to that. In the meanwhile, lets focus on the question. Please see my answer and the conversation between me and the one who posted the question, Thanks.
  • Prashant Lakhlani
    Prashant Lakhlani over 10 years
    Ok, you can use your code as it is with two changes. 1 - Add enctype attribute in form tag. 2- Add ClientIDMode="Static" in page directive.
  • IT researcher
    IT researcher over 10 years
    It works fine.But on attaching file can i get a label near the button as "filename is attached" which is deafult property of file upload control.It will be helpful if i able to do that
  • IT researcher
    IT researcher over 10 years
    Hey it prints path of the file selected.Also it is not proper.In chrome it prints "C:\fakepath\" and followed by filename of the file i selected. What is this "C:\fakepath\" which appends to any file i selected?How it can be corrected? I want only filename.(In IE6 it displays full path to the file,In mozilla it prints only file name,but in chrome it includes fakepath with the name)
  • afzalulh
    afzalulh over 10 years
    I have updated the answer to show only file name, not the path. For security reason most of the browsers are hiding file's real path and showing fake path. Please check this discussion here
  • IT researcher
    IT researcher over 10 years
    Hey the answer you mentioned works on the basis of css.By placing button over a upload control.But how to position the button properly so that when button clicked browse opens.Different browser display upload control differently and so sometimes even if i click outside button upload control clicked and windows opens.Is there anything i can do to fix it?
  • afzalulh
    afzalulh over 10 years
    You can use css hack. Browsers other than ie will share same style. Then add hack for ie. Here's a resource:Conditional comments.
  • Raptor
    Raptor over 10 years
    IE < 9 does not allow JS to auto-submit the form if file upload exists