html5 ajax上传文件asp.net示例

  在Gecko(firefox4+)和webkit(chrome)核心的浏览器中存在FormData对象,可以收集表单中的文件内容,结合ajax对象XMLHttpRequest就可以无刷新的上传文件了。FormData对象实例有一个方法叫做append,允许加入任何形式的数据(文本和文件)的对象。不过悲催的是IE9虽然支持html5,但是没有FormData对象。

  测试代码

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>html5 ajax上传文件asp.net示例</title>
</head>
<body>
<h1>html5 ajax上传文件asp.net示例</h1>
<script type="text/javascript">
    function xhrupload(fd, url) {
        var xhr = new XMLHttpRequest();
        xhr.open("post", url, true);
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                if (200 == xhr.status) {
                    alert(xhr.responseText);
                }
                else alert('发生错误\nstatus:' + xhr.status + '\n返回内容:' + xhr.responseText);
            }
        }
        xhr.send(fd);
    }
    function upload(f) {
        if (window.FormData) {
            var fd = new FormData();
            fd.append("title", f.title.value);
            fd.append("file", f.file.files[0]);
            xhrupload(fd, 'upload.ashx');
            return false;//阻止表单提交
        }
        else {
            alert('不支持html5 ajax上传,使用普通表单上传!');
        }
    }
</script>
<form method="post" onsubmit="return upload(this)" action="upload.ashx" enctype="multipart/form-data">
文件标题:<input type="text" name="title" /><br />
选择文件:<input type="file" name="file" /><input type="submit" value="上传" />
</form>
</body></html>

upload.ashx

<%@ WebHandler Language="C#" Class="upload" %>
using System;
using System.Web;
public class upload : IHttpHandler, System.Web.SessionState.IRequiresSessionState
{
    public void ProcessRequest(HttpContext context)
    {
        HttpPostedFile f = context.Request.Files["file"];
        if (f != null && f.FileName != "")
        {
            string title=context.Request.Form["title"];
            f.SaveAs(context.Server.MapPath("upload/" + f.FileName));
            context.Response.Write("保存成功!\ntitle:"+title+"\n文件名:"+f.FileName+"\n"+DateTime.Now);
        }
        else context.Response.Write("请选择文件!");
    }
    public bool IsReusable {
        get {
            return false;
        }
    }
}

 

加支付宝好友偷能量挖...


原创文章,转载请注明出处:html5 ajax上传文件asp.net示例

评论(0)Web开发网
阅读(4261)喜欢(1)JavaScript/Ajax开发技巧