HTML5拖拽多文件上传asp.net示例

  使用html5的拖放事件实现监控文件的拖拽,然后使用FormData及XMLHttpRequest对象将文件上传到服务器。更多XMLHttpRequest新特性参考此文:XMLHttpRequest Level 2新特性介绍

  如果你的浏览器拖拽文件不是执行上传操作而是在浏览器打开或者弹出保存对话框,那么你的浏览器应该不支持拖放上传功能,请使用firefox或者chrome来测试。

HTML5拖拽多文件上传asp.net示例

  源代码如下

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>HTML5拖拽多文件上传asp.net示例</title>
</head>
<body>
	<div id="dropbox" style="min-width:300px;min-height:100px;border:3px dashed silver;line-height:100px;text-align:center">将需要上传的图片文件拖放到这里</div>
    <div id="loading"></div>
	<script type="text/javascript">
	    function bindEvent() {
	        var dropbox = document.getElementById('dropbox');
	        document.addEventListener("dragenter", function (e) {
	            dropbox.style.borderColor = 'red'; 
	        }, false);
	        document.addEventListener("dragleave", function (e) {
	            dropbox.style.borderColor = 'silver';
	        }, false);
	        dropbox.addEventListener("dragenter", function (e) {
	            dropbox.style.borderColor = 'gray';
	            dropbox.style.backgroundColor = 'white';
	        }, false);
	        dropbox.addEventListener("dragleave", function (e) {
	            dropbox.style.backgroundColor = 'transparent';
	        }, false);
	        dropbox.addEventListener("dragenter", function (e) {
	            e.stopPropagation();
	            e.preventDefault();
	        }, false);
	        dropbox.addEventListener("dragover", function (e) {
	            e.stopPropagation();
	            e.preventDefault();
	        }, false);
	        dropbox.addEventListener("drop", function (e) {
	            e.stopPropagation();
	            e.preventDefault();
	            handleFiles(e.dataTransfer.files);
	        }, false);
	    }
	    window.onload = bindEvent;
	    function handleFiles(files) {
	        var fd = new FormData()//使用html5新对象FormData,这样就不需要构造普通表单提交时的multipart/form-data格式的数据
            , f;
	        for (var i = 0, j = files.length; i < j; i++) {
	            f = files[i];
	            fd.append('file' + i, f);
	        }
	        xhrupload(fd, 'upload.ashx');
	    }
	    function xhrupload(fd, url) {//XMLHttpRequest无刷新上传文件件
	        var xhr = new XMLHttpRequest();
            var loading=document.getElementById('loading');
	        xhr.open("post", url, true);
	        xhr.upload.addEventListener("progress", function (e) {
	            if (e.lengthComputable) {
	                var percentage = Math.round((e.loaded * 100) / e.total);
	                loading.innerHTML = '已经完成' + percentage + '%';
	            }
	            else loading.innerHTML = '正在上传,请稍后...';
	        }, false); 
            //xhr.upload有load事件,但是在事件中获取不到responseText属性,所以还得需要onreadystatechange转换函数
	        xhr.onreadystatechange = function () {
	            if (4 == xhr.readyState) {
	                if (200 == xhr.status) {
	                    if (xhr.responseText == '1') loading.innerHTML = '上传成功!';
	                    else loading.innerHTML = '上传失败!
返回内容:' + xhr.responseText;
	                }
	                else loading.innerHTML = '动态页有问题
Status:' + xhr.status + '
返回内容:' + xhr.responseText;
	            }
	        };
	        xhr.send(fd);
	    }
	</script>
</body>
</html>

save.ashx

<%@ WebHandler Language="C#" Class="upload" Debug="true" %>
using System;
using System.Web;
public class upload : IHttpHandler, System.Web.SessionState.IRequiresSessionState
{
    public void ProcessRequest(HttpContext context)
    {
        if (context.Request.Files.Count > 0)
        {
            for (int i = 0, j = context.Request.Files.Count; i < j; i++)
            {
                HttpPostedFile f = context.Request.Files[i];
                f.SaveAs(context.Server.MapPath("upload/" + f.FileName));
            }
            //不能使用foreach遍历HttpFileCollection对象,要不有些时候会报无法将类型为“System.String”的对象强制转换为类型“System.Web.HttpPostedFile”。错误
            /*foreach (HttpPostedFile f in context.Request.Files)
                if (f.FileName != "")
                {
                    f.SaveAs(context.Server.MapPath("upload/" + f.FileName));
                }*/
            context.Response.Write(1);
        }
        else context.Response.Write("没有文件上传!");
    }
    public bool IsReusable {
        get {
            return false;
        }
    }
}

 


原创文章,转载请注明出处:HTML5拖拽多文件上传asp.net示例

评论(0)Web开发网
阅读(447)喜欢(0)不喜欢(0)Asp.Net/C#