How to get FileUpload to control file download immediately after clicking Browse?

So far I have used 2 controls (FileUpload and an extra button). After the file was selected in the fileUpload control, the user had to accept his choice by clicking the save button.

Here is the button code:

    protected void Button1_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            FileUpload1.SaveAs(Server.MapPath("~/file.jpg"));
            Label1.Text = Server.MapPath("~/file.jpg");
            Image1.ImageUrl = "file.jpg";
        }
    }

I am wondering if there is a way to avoid using this button, so the FileUpload control button will do the additional task of the button.

+5
source share
1 answer

The control FileUploaddisplays <input type="file>in the browser. You can use javascript changeto start the download.

, load, body :

<body onload="body_onload()">

:

<script type="text/javascript">
    function body_onload()
    {
        ...

        $get('<%=FileUpload.ClientID%>').onchange = function() { 
            $get('<%=this.Page.Form.ClientID%>').submit(); 
        };
    }
</script>

, jQuery, head ( jQuery):

<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>

( #fileUpload1 #form1 FileUpload Form):

<script type="text/javascript">
    $(document).ready(function() {
        $("#fileUpload1").change(function() {
            $("#form1").submit();
        });
    });
</script>
+4

All Articles