ASP.NET - 使用 JavaScript 和 C# 上传文件






4.38/5 (15投票s)
ASP.NET - 上传文件时显示加载图像
引言
很多时候,当我们使用 FileUpload 控件时,我们希望使用 AJAX 行为上传提交的文件,因此我们不希望将整个页面回发到服务器。此外,我们希望在上传文件时显示加载图像。本文讨论了如何做到这一点。
Using the Code
那么,我们该如何实现呢?首先,我们将创建一个 ASPX 页面(FileUpload.aspx)。此页面将包含许多控件,但最重要的控件是
- FileUpload 控件
- Button 控件
此页面的后台代码将是正常的代码,用于在单击按钮时保存文件
protected void btnUpload_Click(object sender, EventArgs e)
{   
          //Get the root folder from web config.
          string rootFolder = ConfigurationManager.AppSettings["RootFolder"].ToString();
          //Get the full file path which we will use to save the file.
          string fileName = rootFolder + @"ProfileName.doc";
          //Save the file on the specified path
          FileUpload1.SaveAs(fileName);
          //Hide the upload panel
          pnlUpload.Visible = false;
          //View message to notify the user that his/her file has been uploaded.
          pnlAfterUpload.Visible = true;
}
很简单,对吧?那么,之后我们需要做的就是创建另一个页面(Default.aspx)。此页面中没有代码。在 HTML 中,我们将添加一个 iframe,此 iframe 的 source 属性值是 FileUpload.aspx 页面。我们还将在 HTML 中添加一个 image 标签用于加载图像,如下所示
<div  style="border-width:1px;border-bottom-style:solid;border-color:#F3F3F3">
        <iframe id="iUploadFile" frameborder="0" src="IFrame/FileUpload.aspx">
        
        </iframe>
     <img id="imgLoading" src="Images/loading.gif" style="display:none" />
</div>
现在最后一步是修改我们的代码,以便在单击 FileUpload.aspx 中的提交按钮时显示 image 并隐藏 iframe ,并在上传文件完成后隐藏 image 并再次显示 iframe 。为了实现这一点,我们需要将以下 JavaScript 函数添加到 (FileUpload.aspx) 页面
function HideProgress()
{
    parent.document.getElementById("imgLoading").style.display= 'none';
    parent.document.getElementById("iUploadFile").style.display= 'block';
}
function ShowProgress()
{
    parent.document.getElementById("imgLoading").style.display= 'block';
    parent.document.getElementById("iUploadFile").style.display= 'none';
}
现在,我们只需要在单击提交按钮时调用 ShowProgress() 函数。为了实现这一点,我们需要将按钮的 OnClientClick 属性设置为
<asp:Button ForeColor="#FFFFFF" BackColor="#00cc00" OnClientClick="ShowProgress();"
Text="Upload Your File" ID="btnUpload" runat="server" OnClick="btnUpload_Click" />
然后,我们需要在上传文件完成后调用 HideProgress() 函数。我们需要在 (FileUpload.aspx) 页面的后台代码中用于保存文件的代码的末尾添加以下代码行
//Call JavaScript function to hide progress bar image
        Page.ClientScript.RegisterStartupScript(this.GetType()
                                                , @"CloseProgressbar",
                                                @"HideProgress();", true);


