Html代碼javascript
<form enctype="multipart/form-data" action="UploadFile_1" method="post" target="frameResult"> <div class="item"> <input id="File1" name="UserPhoto" type="file" value="" /> <input type="submit" value="提交上傳" /> <iframe src="about:blank" id="frameResult" name="frameResult"></iframe> </div> </form>
後臺代碼(ASP.NET MVC)html
[HttpPost] public ActionResult UploadFile_1() { string result = "上傳成功"; HttpPostedFileBase file= Request.Files["UserPhoto"]; file.SaveAs(Server.MapPath("~/Upload/")+ file.FileName); return Content(result); }
JavaScript代碼,由於不須要<form>標籤,html也沒什麼內容可貼的了。html5
var btnUpload = document.getElementById('btnUpload'); btnUpload.onclick = function () { var fileInput = document.getElementById('File2'); if (!fileInput.value) { return; } var feature = {}; feature.fileapi = fileInput.files !== undefined; feature.formdata = (typeof window.FormData !== 'undefined'); if (!feature.fileapi || !feature.formdata) { showMessage('當前瀏覽器不支持Html5,請更換高級瀏覽器'); return; } var xhr = new XMLHttpRequest(); var formData = new FormData(); formData.append("UserPhoto", fileInput.files[0]); xhr.open("post", './UploadFile_2'); //超時時間,單位是毫秒 xhr.timeout = 60 * 1000; //請求結束 xhr.onload = function (event) { if (xhr.status == 200) { showMessage("上傳成功"); return; } if (xhr.status == 404) { showMessage("請求路徑錯誤"); setProgressBar(0, 'kb/s', 'hide', '0%'); return; } if (xhr.status == 500) { console.error('xhr.status == 500'); showMessage("服務器異常"); } }; //請求異常(不包括404) xhr.onerror = function () { console.error('xhr.onerror'); showMessage("請求發生異常"); }; //上傳開始事件 xhr.upload.onloadstart = function () { setProgressBar(0, 'kb/s', 'hide', '0%'); lastTime = new Date().getTime(); loadSize = 0; } //上傳過程事件,間歇調用該方法用來獲取上傳過程當中的信息 xhr.upload.onprogress = function (event) { //ProgressEvent.lengthComputable:boolean類型,表示可否計算出文件長度;若是爲false,那麼ProgressEvent.total則爲0. //簡而言之,lengthComputabl等於true就能夠作進度計算 if (!event.lengthComputable) { return; } //計算上傳速度,event.loaded是已發送的大小 var now = new Date().getTime(); var timeInterval = (now - lastTime) / 1000; lastTime = now; var sizeInterval = event.loaded - loadSize; loadSize = event.loaded; var speed = sizeInterval / timeInterval; // 單位b/s var bspeed = speed; var units = "b/s"; if (speed / 1024 > 1) { speed = speed / 1024; units = 'kb/s'; } if (speed / 1024 > 1) { speed = speed / 1024; units = 'mb/s'; } speed = speed.toFixed(1); //計算剩餘時間 var resttime = ((event.total - event.loaded) / bspeed).toFixed(1); //單位 秒 //計算進度百分比 var precent = (100 * event.loaded / event.total); pre = Math.floor(precent); if (bspeed == 0) { //setProgressBar方法是控制進度條的, //這裏代碼沒貼,在最後源碼下載裏有 //四個參數:上傳速度、單位、剩餘時間、進度百分比 setProgressBar(0, "b/s", 'infinity', 'noChange'); } else { setProgressBar(speed, units, resttime, precent + '%'); } }; //上傳終止 xhr.upload.onabort = function () { console.info('xhr.upload.onabort'); } //上傳異常事件 //當網絡環境正常時,XMLHttpRequest.status等於40四、500並不能觸發upload.onerror事件 //當網絡環境異常時(offline),會觸發upload.onerror事件 xhr.upload.onerror = function () { console.error('xhr.upload.onerror'); } //文件發送完畢事件 //當網絡環境正常時,即便XMLHttpRequest.status等於40四、500,仍會被觸發upload.onload事件 //當網絡環境異常時(offline),不會觸發upload.onload事件 xhr.upload.onload = function () { console.info('xhr.upload.onload'); } //上傳超時 xhr.upload.ontimeout = function () { console.error('xhr.upload.ontimeout'); } //發送請求 xhr.send(formData); }
後臺接收代碼java
[HttpPost] public ActionResult UploadFile_2() { HttpPostedFileBase file = Request.Files["UserPhoto"]; file.SaveAs(Server.MapPath("~/Upload/") + file.FileName); return Json("success"); }
$('#btnUpload3').click(function () { var $fileInput = $('#File3'); if (!$fileInput.val()) { return; } var feature = {}; //檢查是否支持html5 api feature.fileapi = $fileInput.get(0).files !== undefined; feature.formdata = (typeof window.FormData !== 'undefined'); if (!feature.fileapi || !feature.formdata) { showMessage('當前瀏覽器不支持Html5,請更換高級瀏覽器'); return; } var formData = new FormData(); formData.append("UserPhoto", $fileInput[0].files[0]); $.ajax({ type: 'post', url: './UploadFile_2', data: formData, processData: false,//設置爲false。由於data值是FormData對象,不須要對數據作處理。 contentType: false, //設置爲false。告訴jQuery不要去設置Content-Type請求頭 xhr: function () { var xhr = $.ajaxSettings.xhr(); if (xhr.upload) { xhr.upload.onloadstart = uploadStart; xhr.upload.onprogress = uploadProgress; return xhr; } }, success: function (data, textStatus, jqXHR) { showMessage("上傳成功"); }, error: function (jqXHR, textStatus, errorThrown) { showMessage("上傳失敗"); } }); });
html代碼jquery
<form id="form4" enctype="multipart/form-data" action="UploadFile_2" method="post"> <div class="item"> <h3> 四、異步表單插件jquery.form.js </h3> <input id="File4" name="UserPhoto" type="file" value="" /> <input id="btnUpload4" type="button" value="提交上傳" /> </div> </form>
js代碼ajax
$('#btnUpload4').click(function () { var $fileInput = $('#File4'); if (!$fileInput.val()) { return; } var options = { type: 'post', url: './UploadFile_2', success: function (data, textStatus, jqXHR) { showMessage("上傳成功"); }, error: function (jqXHR, textStatus, errorThrown) { showMessage("上傳失敗"); } } var feature = {}; //檢查是否支持html5 api feature.fileapi = $fileInput.get(0).files !== undefined; feature.formdata = (typeof window.FormData !== 'undefined'); //若是支持html5,那麼就使用進度條 if (feature.fileapi && feature.formdata) { options = $.extend(options, { xhr: function () { var xhr = $.ajaxSettings.xhr(); if (xhr.upload) { xhr.upload.onloadstart = uploadStart; xhr.upload.onprogress = uploadProgress; return xhr; } } }); } $("#form4").ajaxSubmit(options); });
源碼下載:https://pan.baidu.com/s/1eWiOzvio9EVW2WlYeaKUGAapi
代碼是用VS2015 ASP.NET MVC5寫的,我把bin目錄內的dll都刪了,經過還原 nuget 程序包應該就能運行了。瀏覽器