How to upload a file without page refresh

Posted by Anuraj on Thursday, July 25, 2013

.Net ASP.Net

This is an old ASP.Net hack to upload file without page refresh in ASP.Net web pages.

Implementation

You couldn’t upload a file without post back using normal file upload control. (Yes I agree with Ajax Toolkit or using HTML5 it is possible). To achieve the no refresh or no postback, we are placing the File upload control and upload button in a Web page (upload.aspx) and in the main page (default.aspx) we will be loading the File upload page in an IFRAME.

For displaying upload progress, a GIF image is used, the style of the image will be none by default. In the upload button onClientClick event, the display style will be changed to block.

Source code Here is the markup of Upload.aspx page.

<asp:FileUpload runat="server" ID="fileUpload" />
<asp:Button runat="server" 
    ID="cmdUpload" Text="Upload"
    OnClick="cmdUpload_Click"
    OnClientClick="javascript:document.getElementById('lodingDiv').style.display = 'block';" />
<div style="display: none;" id="lodingDiv">
    <asp:Image runat="server" 
    ID="imgLoading" ImageUrl="~/ajax-loader.gif" />
</div>
<asp:Label runat="server" ID="lblInfo" />

And here is the code behind.

protected void cmdUpload_Click(object sender, EventArgs e)
{
    fileUpload.SaveAs(
        Path.Combine(Request.MapPath("~/Images"), fileUpload.FileName));
    lblInfo.Text = "File uploaded successfully !!!";
}

And here is the markup of default page.

## 
    File Upload Demo


<iframe runat="server" src="Upload.aspx" 
style="border: 0px none #FFF"></iframe>

There is no code in the code behind file of default.aspx.

As I mentioned in the top it is a hack, if you need a real solution, either you can use HTML5 File API and XHR or you can use AjaxToolkit Async File upload control.

Happy Coding.



Did you like this article? Share it with your friends

Facebook Twitter Google+ LinkedIn Reddit StumbleUpon



Subscribe


Copyright © 2017 - Anuraj P. Blog content licensed under the Creative Commons CC BY 2.5 | Unless otherwise stated or granted, code samples licensed under the MIT license. This is a personal blog. The opinions expressed here represent my own and not those of my employer. Hosted with ❤ by GitHub