兩者最大的區(qū)別就是:表單上傳過程中榔昔,整個(gè)頁(yè)面就刷新了槽袄;而異步上傳就可以達(dá)到只刷新局部位置掌呜!
參考文章地址:[https://www.cnblogs.com/fengxuehuanlin/p/5311648.html]
1 異步上傳:
1.1html
image.png
1.2 js腳本
function uploadFiles() {
if (!$('#fileUpload').val()) return;
$("#uploadInfo").html("");
$.ajaxFileUpload({
url: "@Url.Action("FileToLoad", "Card")",//用于文件上傳的服務(wù)器端請(qǐng)求地址
secureuri: false,//一般設(shè)置為false
fileElementId: "fileUpload",//文件上傳標(biāo)簽元素的Id
dataType: "json", //返回值類型凡人,一般設(shè)置為json
type: "POST",//請(qǐng)求方式
success: function (data, status) //服務(wù)器響應(yīng)成功后名党,處理函數(shù)
{
if (data.Success) {
$("#FileIdhidden").val(data.ObjectId);
$("#uploadInfo").html("上傳成功,共計(jì):"+ data.Count+"條");
} else {
alert("上傳失斈又帷:" + data.Message);
}
},
error: function (data, status, e) //服務(wù)器響應(yīng)失敗后传睹,處理函數(shù)
Oudao.ShowMessage(false, "上傳文件失敗,請(qǐng)確認(rèn)上傳文件是否存在或文件格式是否有效岸晦!");
},
onComplete: function (filename, response) {//請(qǐng)求完成后蒋歌,處理函數(shù)
$('#fileUpload').val("");
$("#uploadInfo").html("");
}
});
}
1.3后端接口
對(duì)上傳文件的處理
[HttpPost]
public ActionResult FileToLoad()
{
JsonResultData result = new JsonResultData();
result.Success = false;
result.Message = "上傳文件失敗委煤!";
if (Request.Files.Count > 0)
{
HttpPostedFileBase filetoLoad = Request.Files[0];
string newFileName = Guid.NewGuid().ToString("N");
string path = Server.MapPath(ConstString.FileLoadPath.CardFileUpload); //臨時(shí)目錄
if (!System.IO.Directory.Exists(path))
{
System.IO.Directory.CreateDirectory(path);
}
string filePath = Path.Combine(path, newFileName);
filetoLoad.SaveAs(filePath);
try
{
var lines = System.IO.File.ReadLines(filePath);
result.Success = true;
result.Message = "ok.";
result.ObjectId = newFileName;
result.Count = lines.Count();
}
catch (Exception ex)
{
result.Success = false;
result.Message = "讀取文件失斕糜汀:" + ex.Message;
System.IO.File.Delete(filePath);
}
}
var content = SerializeHelper.GetJson(result);
return Content(content, "text/html");
}
注:表單提交中的 "button"按鈕,不需要type類型碧绞,或者type="Submit"
[圖片上傳中...(image.png-ac9a5e-1575880787952-0)]
2 同步上傳
[https://www.cnblogs.com/fengxuehuanlin/p/5311648.html]