2、在控制器内创建如下方法
//文件上传
public ActionResult uploadFile(HttpPostedFileBase file)
{
if (file == null)
{
return Json(new { result = "false", errorMsg="文件不存在" }, "text/html");
}
string fileName = "~/UploadFiles/" + DateTime.Now.ToString("yyyyMMddHHssmm") + Path.GetFileName(file.FileName);
var physicsFileName = Server.MapPath(fileName);
try
{
file.SaveAs(physicsFileName);
return Json(new { result = "true", imgUrl = fileName }, "text/html");
}
catch(Exception ex)
{
return Json(new { result = "false", errorMsg = ex.Message }, "text/html");
}
}
3、在前端编写如下JS,需要引入JQuery和ajaxfileupload.js
<script type="text/javascript">
function ajaxFileUploads() {
$("#loading").ajaxStart(function () {
$(this).show();
}).ajaxComplete(function () {
$(this).hide();
});
$.ajaxFileUpload({
url: '/User/uploadFile', //后台处理的 - Controller/Action
secureuri: false,
fileElementId: 'fileToUpload', //上传文件的Name属性
dataType: 'json',
type: 'post',
success: function (data, status) {
alert(data.result);
if (data.result === "true") { //成功后把后台文件路径赋值给异常控件,便于一起提交给后台
alert(data.imgUrl);
$(".imgUrl").val(data.imgUrl);
} else if (data.result === "false") {
alert(data.errorMsg);
}
},
error: function (data, status, e) {
alert(e);
}
})
return false;
}
$(document).ready(function () {
$(".btnUpload").click(function () {
ajaxFileUploads();
});
});
</script>
4、View中的代码
<div>
个人头像:@Html.HiddenFor(m => m.imgUrl, new { @class = "imgUrl" }) //强类型绑定
<input type="file" id="fileToUpload" name="file" /><input type="button" class="btnUpload" value="上传" /> //上传控件和上传按钮
<span id="loading" style="display: none;">请等待</span> //等待提示
</div>