###index.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <script src="https://www.atool.online/article/Script/jquery-1.10.2.min.js"></script>
  <script src="https://www.atool.online/article/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;
    }
  }
}

以上这篇asp.net使用H5新特性实现异步上传的示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持阿兔在线工具。

点赞(0)

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部