asp.net使用H5新特性实现异步上传

###index.hmtl

'''

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <script src="Script/jquery-1.10.2.min.js"></script>
    <script src="Script/index.js"></script>
    <title></title>
    <script type="text/javascript">
        $(function(){
            $("#ajaxFileUpload").click(function () {
                formDataUpload();
            });
        });
    </script>


</head>
<body>
    <input type="file" id="FileToUpload" multiple="multiple" mame="FileToUpload" />
    <input type="button" id="ajaxFileUpload" value="上传"/>
    <input type="text" size="10"/>
</body>
</html>

'''


###index.js

'''

function formDataUpload() {
    //这里可以一次性选中多个文件
    var fileUpload = document.getElementById("FileToUpload").files;
    if (fileUpload.length == 0) {
        alert("请选中文件再上传");
        return;
    }


    //html5新特性
    var formdata = new FormData();
    //添加上传数据
    for (var i = 0; i < fileUpload.length;i++){
        formdata.append('files', fileUpload[i]);
    }




    //使用javascript的原生ajax
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open("post", 'Handler.ashx?method=formDataUpload');
    xmlHttp.onreadystatechange = function () {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
            alert("上传成功");
        }
    }
    xmlHttp.send(formdata);


}

'''

###handler.ashx

'''

<%@ WebHandler Language="C#" Class="Handler" %>


using System;
using System.Web;


public class Handler : IHttpHandler {
        
    public void ProcessRequest (HttpContext context) {
        formDataUpload(context);
    }


    public static void formDataUpload(HttpContext context) {
        //获取到客户端提交的文件
        HttpFileCollection files = context.Request.Files;
        string msg = string.Empty;
        string error = string.Empty;
        int fileM = 0;
        if (files.Count > 0) {
            for (int i = 0; i < files.Count; i++) {           ;
                String path = @"D:\"+files[i].FileName;
                files[i].SaveAs(path);
                fileM += files[i].ContentLength;
            }
            msg = "上传成功,文件总大小:" + fileM;
            string res = "{error :'" + error + "',msg:'" + msg + "'}";
            context.Response.Write(res);
            context.Response.End();
        }
    }


    public bool IsReusable {
        get {
            return false;
        }
    }


}

'''


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值