一、脚本引入
<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"; }
原文链接:https://www.f2er.com/ajax/163591.html