小编给大家分享一下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;
}
}
}
看完了这篇文章,相信你对“asp.net如何使用H5新特性实现异步上传”有了一定的了解,如果想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。