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

栏目: 编程语言 · ASP.NET · 发布时间: 7年前

内容简介:下面小编就为大家分享一篇asp.net使用H5新特性实现异步上传的示例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Developing Large Web Applications

Developing Large Web Applications

Kyle Loudon / Yahoo Press / 2010-3-15 / USD 34.99

As web applications grow, so do the challenges. These applications need to live up to demanding performance requirements, and be reliable around the clock every day of the year. And they need to withs......一起来看看 《Developing Large Web Applications》 这本书的介绍吧!

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具