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

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

查看所有标签

猜你喜欢:

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

ACM/ICPC程序设计与分析

ACM/ICPC程序设计与分析

沈云付 / 清华大学 / 2010-7 / 39.50元

《ACM/ICPC程序设计与分析(C++实现)》介绍ACM国际大学生程序设计竞赛概况及程序设计基础,系统介绍数论、组合数学、动态规划、计算几何、搜索、图论和网络流等专题的典型算法,挑选历年竞赛中许多有代表性的竞赛题作为例题进行分析,便于学生编程时模仿学习。每章的例题和习题都配有输入输出样例,方便学生在编程时测试与调试程序。《ACM/ICPC程序设计与分析(C++实现)》以C++为程序设计语言,以提......一起来看看 《ACM/ICPC程序设计与分析》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

URL 编码/解码
URL 编码/解码

URL 编码/解码