asp. net example of asynchronous upload using new features of H5
- 2021-10-24 19:20:27
- OfStack
###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=" Upload "/>
<input type="text" size="10"/>
</body>
</html>
###index.js
function formDataUpload() {
// Here you can 1 Sequentially select multiple files
var fileUpload = document.getElementById("FileToUpload").files;
if (fileUpload.length == 0) {
alert(" Please select the file before uploading ");
return;
}
//html5 New features
var formdata = new FormData();
// Add uploaded data
for (var i = 0; i < fileUpload.length;i++){
formdata.append('files', fileUpload[i]);
}
// Use javascript Native of ajax
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("post", 'Handler.ashx?method=formDataUpload');
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
alert(" Upload succeeded ");
}
}
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) {
// Get the file submitted to the client
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 = " Upload successful, total file size :" + fileM;
string res = "{error :'" + error + "',msg:'" + msg + "'}";
context.Response.Write(res);
context.Response.End();
}
}
public bool IsReusable {
get {
return false;
}
}
}