基于jQuery通过jQuery.form.js插件实现异步上传
本文主要从前台和后台代码分析了jquery.form.js实现异步上传的方法,分享给大家,具体代码如下
前台代码:
@{
Layout=null;
}
<!DOCTYPEhtml>
<html>
<head>
<metaname="viewport"content="width=device-width"/>
<scriptsrc="~/Scripts/jquery-1.7.2.min.js"></script>
<scriptsrc="~/Scripts/jquery.form.js"></script>
<title>upload</title>
</head>
<body>
<formid="fileForm"method="post"enctype="multipart/form-data"action="/upload/upload">
文件名称:<inputname="fileName"type="text"><br/>
上传文件:<inputname="myfile"type="file"multiple="multiple"><br/>
<inputid="submitBtn"type="submit"value="提交">
<imgsrc="#"alt="myimg"id="iceImg"width="300"height="300"style="display:block;"/>
</form>
<inputtype="text"name="height"value="170"/>
<inputid="sbtn2"type="button"value="提交表单2">
<inputtype="text"name="userName"value=""/>
<scripttype="text/javascript">
$(function(){
$("#fileForm").ajaxForm({
//定义返回JSON数据,还包括xml和script格式
//clearFormBoolean值属性,表示是否在表单提交成功后情况表单数据
//dataType提交成果后返回的数据格式,可选值包括xml,json或者script
//target服务器返回信息去更新的页面对象,可以是jquery选择器字符串或者jquer对象或者DOM对象。
//type提交类型可以是”GET“或者”POST“
//url表单提交的路径
dataType:'json',
beforeSend:function(){
//表单提交前做表单验证
$("#myh1").show();
},
success:function(data){
//提交成功后调用
//alert(data.message);
$("#iceImg").attr('src','/upload/img/'+data.fileName);
$("#myh1").hide();
//防止重复提交的方法
//1.0清空表单数据
$('#fileForm').clearForm();
//2.0禁用提交按钮
//3.0跳转页面
}
});
$("#myfile").change(function(){
$("#submitBtn").click();
});
$("#iceImg").click(function(){
$("#myfile").click();
});
});
</script>
<h1id="myh1"style="display:none;">加载中...</h1>
</body>
</html>
后台代码:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Drawing;
usingSystem.Linq;
usingSystem.Web;
usingSystem.Web.Mvc;
namespaceIceMvc.Controllers
{
publicclassUploadController:Controller
{
//
//GET:/Upload/
publicActionResultIndex()
{
returnView();
}
[HttpPost]
publicActionResultUpload()
{
varfilesList=Request.Files;
for(inti=0;i<filesList.Count;i++)
{
varfile=filesList[i];
if(file.ContentLength>0)
{
if(file.ContentLength>5242880)
{
returnContent("<script>alert('注册失败!因为您选择图片文件不能大于5M.');window.location='/User/Register';</script>");
}
//得到原图的后缀
stringextName=System.IO.Path.GetExtension(file.FileName);
//生成新的名称
stringnewName=Guid.NewGuid()+extName;
stringimgPath=Server.MapPath("/upload/img/")+newName;
if(file.ContentType.Contains("image/"))
{
using(Imageimg=Image.FromStream(file.InputStream))
{
img.Save(imgPath);
}
varobj=new{fileName=newName};
returnJson(obj);
}
else
{
//returnContent("<script>alert('注册失败!因为您未选择图片文件.');window.location='/User/Register';</script>");
}
}
}
returnContent("");
}
publicActionResultAfupload()
{
returnView();
}
}
}
以上就是针对jquery.form.js实现异步上传的方法,希望对大家的学习有所帮助。