###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() { //這里可以一次性選中多個(gè)文件 var fileUpload = document.getElementById("FileToUpload").files; if (fileUpload.length == 0) { alert("請(qǐng)選中文件再上傳"); return; } //html5新特性 var formdata = new FormData(); //添加上傳數(shù)據(jù) 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新特性實(shí)現(xiàn)異步上傳的示例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com