65.9K
CodeProject 正在变化。 阅读更多。
Home

AJAX 式文件上传

starIconstarIconstarIconstarIconstarIcon

5.00/5 (2投票s)

2010 年 4 月 11 日

CPOL

2分钟阅读

viewsIcon

20593

本文档解释了如何在网页上提供文件上传功能,模拟 AJAX 行为。

引言

目前,在不刷新页面的情况下,无法直接在网页上上传文件。如果您有一个启用了 AJAX 的交互式页面,您希望以类似于 AJAX 行为的方式支持上传文件。

不幸的是,XMLHttpRequest 对象不支持上传文件;因此,我尝试使用一种变通方法来上传文件。

背景

首先,在深入主题之前,让我们回顾一下 HTML 表单的一些基本概念。如果您已经熟悉 HTML 表单,可以跳过此部分。

基本上,有两种主要的提交表单的方式。第一种是通过单击类型为 submit 的输入控件。例如:

<input type="submit" id="mySubmitButton" name="mySubmitButton" value="Submit Form" />

另一种方式是调用提交表单的 JavaScript 代码,例如:

function submitMyForm() {
    var theForm = document.forms['myForm'];    
    theForm.submit();
}

HTML 表单具有几个属性,指示应如何提交表单;以下是一些这些属性:

  • action:它是应提交表单到的网页的路径
  • method:提交表单的方法(可能的值包括:POST、GET 等)
  • enctype:应加密提交的数据的方式
  • target:应提交表单的框架

一旦页面被提交,无论是通过单击“提交”按钮还是通过调用提交表单的 JavaScript,浏览器都会检查表单的 action,然后它将加载 action - 网页 - 并将表单的内容发送给它,使用在 encrypt 属性中指定的加密方法进行加密。

准备页面

将使用两个页面来实现此技术。第一个页面将包含 HTML 内容,包括文件上传控件。第二个页面将包含将文件保存到服务器的服务器端代码。

让我们首先将控件添加到第一个页面。当然,我们需要添加一个文件上传控件。此外,我们将添加一个 iFrame 和一个表单。页面的 HTML 主体如下所示:

<body>

    <!-- This is the form that we added -->
    <form id="myForm" name="myForm" target="myIFrame" method="post" action="SaveFile.aspx"
        enctype="multipart/form-data">
    </form>
    
    <!-- This is the form which is added by default -->
    <form id="form1" runat="server">
    
        <!-- This is the file upload control -->
        <input type="file" id="myFile" name="myFile" runat="server" />
        
        <!-- This is a normal button that will be used 
             to the JavaScript function to upload the file -->
        <input type="button" value="Upload File" />
        
        <!-- This is an iFrame in which the form will be submitted -->
        <iframe style="display: none;" id="myIFrame" name="myIFrame"></iframe>
    
    </form>
</body>

请注意,我们将表单添加到页面默认添加的表单之外。我们还将 action 属性设置为第二个页面的 URL,如前所述。iFrame 样式设置为保持隐藏,这样我们就不会注意到文件上传时它了。

JavaScript

现在,我们希望让按钮调用 JavaScript 来提交表单并上传文件。为了做到这一点,我们将向页面添加一个 JavaScript 函数并将其命名为 uploadFile。我们还将在按钮的单击事件中调用此函数。以下是 JavaScript 函数:

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

    // get the form that we added
    var theForm = document.forms['myForm'];
    
    // some browsers don't recognize the line above,
    // so this line is added for browser compatability
    if (!theForm)
        theForm = document.myForm;    

    if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
    
        // get the file upload control
        var theFile = document.getElementById("myFile");
        
        // add the file upload control inside the form
        theForm.appendChild(theFile);
        
        // submit the form
        theForm.submit();
    }    
}
</script>

保存文件

第二个页面 SaveFile.aspx 包含在加载时保存文件的代码,如下所示:

protected void Page_Load(object sender, EventArgs e)
{
    Request.Files["myFile"].SaveAs("path on the server to save the file");
}

兼容浏览器

此技术在 Microsoft Explorer 8 和 Google Chrome 上进行了测试。

© . All rights reserved.