AjaxForm异步上传表单、图片

前端之家收集整理的这篇文章主要介绍了AjaxForm异步上传表单、图片前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

一、脚本引入

<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<script src="~/Scripts/AjaxForm.js"></script> //下载链接:http://pan.baidu.com/s/1eQ4FSyQ

二、前台代码

@using (Html.BeginForm("QuestionAdd","Manage",FormMethod.Post,new { @id="form1",enctype = "multipart/form-data" }))
{

<input name="questionFile" id="questionFile" type="file" onchange="UploadQuestionFile(this)" />

}

<script type="text/javascript">

function UploadQuestionFile(a) {
var aa = $(a).val();
if (aa != "") {
$("#form1").ajaxSubmit({
type: "post",
async: false,
url: "/Manage/QuestionAddFile",//注意提交方法,和form表单默认的可以不一样啊
success: function (fURL) {
alert("异步上传成功"+fURL);
},
error: function () {
alert("标题图片上传失败!");
}
})
}
}

</script>

三、后台代码

public string QuestionAddFile(HttpPostedFileBase questionFile) { if (questionFile != null) { if (!PicExtensionOk(Path.GetExtension(questionFile.FileName.ToLower()))) { return "-1"; } if (questionFile.HasFile()) { string pathRrelative = @"/UploadFile/";//相对路径 string pathAbsolute = Server.MapPath(@"~\UploadFile\");//绝对路径 if (!Directory.Exists(pathAbsolute)) { Directory.CreateDirectory(pathAbsolute); //新建文件夹 } string fileName = string.Empty; fileName = Guid.NewGuid().ToString() + System.IO.Path.GetExtension(questionFile.FileName); questionFile.SaveAs(pathAbsolute + fileName); return pathRrelative+fileName; } } return "-1"; }

猜你在找的Ajax相关文章