欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-07-05 20:19:07
###index.html

###index.html

<!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;
    }
  }
}

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