下載異步上傳插件AjaxFileUploader,下載地址:http://phpletter.com/DOWNLOAD/javascript
解壓,保存在 asp.net mvc項目的一個文件夾下,以下圖:
1. Controller層
public ActionResult View3()
{
return View();
}
[HttpPost]
public ActionResult View3(HttpPostedFileBase file)
{
if (file == null)
{
return Content("沒有文件!", "text/plain");
}
var fileName = Path.Combine(Request.MapPath("~/UploadFiles"), Path.GetFileName(file.FileName));
try
{
file.SaveAs(fileName);
return Content("上傳成功!", "text/plain");
}
catch
{
return Content("上傳異常 !", "text/plain");
}
}
2. View層:
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>View1</title>
<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<script src="~/ajaxfileupload/jquery.js"></script>
<script src="~/ajaxfileupload/ajaxfileupload.js"></script>
<script type="text/javascript">
function ajaxFileUploads() {
$("#loading").ajaxStart(function () {
$(this).show();
})//開始上傳文件時顯示一個圖片
.ajaxComplete(function () {
$(this).hide();
});//文件上傳完成將圖片隱藏起來
$.ajaxFileUpload({
url: '/Test/View3',//後臺處理的action
secureuri: false,
fileElementId: 'file',//上傳的控件名
dataType: 'text',
success: function (data, status) {
$("#mydiv").html( data);
},
error: function (data, status, e) {
$("#mydiv").html( data + "
" + e);
}
})
return false;
}
</script>
</head>
<body>
<input type="file" id="file" name="file" />
<img src="../ajaxfileupload/loading.gif" width="20px" height="20px" id="loading" style="display: none;">
<span id="mydiv" style="color: green;"></span>
<br />
<input type="button" value="上傳" ajaxFileUploads();">
</body>
</html>