1、将jquery及jquery.form引用进来
<script src="~/Content/JQuery/jquery-1.8.2.js"></script>
<script src="~/Content/JQuery/jquery.form.js"></script>
2、html页面代码
<form id="ajaxForms" enctype="multipart/form-data">
<input id="Files" name="Files" type="file" class="file" />
<input id="Button1" οnclick="Fn_UpLoad()" type="button" value="上传附件" />
</form>
<table id="List"></table>
3、js前台代码
function Fn_UpLoad() {
if (document.getElementById("Files").value) {
$("#ajaxForms").ajaxSubmit({
type: "POST",
url: "/Form/Fn_UpLoad?SaveModuleName=TestFile",
dataType: "text",
success: function (data) {
$("#List").append("<tr><td>" + data + "</td></tr>");
}
});
} else {
alert("请选择附件!");
return;
}
}
4、MVC后台代码
public ActionResult Fn_UpLoad()
{
HttpPostedFileBase files = Request.Files["Files"];
string FileName = files.FileName;
string SaveModuleName = Request["SaveModuleName"].ToString();//文件存放模块
string FilesPath = System.AppDomain.CurrentDomain.BaseDirectory + "Attachment\\" + SaveModuleName;//文件存放路径
//判断文件存放模块是否存在
if (Directory.Exists(FilesPath) == false)
{
Directory.CreateDirectory(FilesPath);
}
//判断文件是否
if (System.IO.File.Exists(FilesPath + "\\" + FileName) == false)
{
files.SaveAs(FilesPath + "\\" + FileName);
}
return Content(FilesPath + "\\" + FileName);
}
6、源代码