Search code examples
c#asp.netdetect

Upload FileUpload


I'm working on a project in which I have to upload .txt files. I'm using asp.net FileUpload. Here is a piece of code:

<div class="custom-file">
    <asp:FileUpload ID="inputFileTXT" CssClass="custom-file-input" runat="server" />
    <label id="lblFileName" runat="server" class="custom-file-label" for="inputFileTXT">Elegir archivo</label>
</div>``

I'm using styles from MDBootstrap.

The thing is that I want to do stuff when a user clicks on the asp:fileUpload element and selects a file WITHOUT CLICKING ON A BUTTON. I've been searching but I didn't find how to detect dynamically this action. The asp:fileUpload has no event such as OnUploading.

PD: I tried using an UpdatePanel but when it makes the postback it seems like the uploaded file disapears. Maybe this is the way but I couldn't make it work.


Solution

  • You can add a dummy LinkButton to the page and leave it empty, but give it an OnClick, in which you would process the file.

    <asp:FileUpload ID="FileUpload1" runat="server" accept="image/*" />
    
    <asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton1_Click"></asp:LinkButton>
    

    Then in code behind add the onchange trigger to the FileUpload control that will do a PostBack of LinkButton1.

    protected void Page_Load(object sender, EventArgs e)
    {
        FileUpload1.Attributes.Add("onchange", "__doPostBack('" + LinkButton1.UniqueID + "','')");
    }
    

    PS do not put a FileUpload Control in an UpdatePanel.