企业级开发,经常遇到图片上传的功能,表单提交不支持文件上传的,
必须form表单上声明是:method="post" enctype="multipart/form-data"。
在项目中遇到后台检验用户名,标题,或者密码之类的是否存在,那么,采用异步上传图片
1.通过ajax异步上传图片到服务器,回调图片的url路径
2.把图片的url路径通过赋值给隐藏的input框或者div,span
3.全部提交表单,ajax提交需要序列化表单
<form name="bannerForm" id="frm_add"
action="${ctx}/contentManage/bannerManage.do?method=save" method="post" enctype="multipart/form-data" >
<div class="input_div">
<label><em style="color:red">*</em>banner图片</label>
<div class=" fileinput fileinput-new" data-provides="fileinput">
<div class="avatar fileinput-preview fileinput-exists thumbnail">
<div id="localImag">
<c:if test="${model.url != null}">
<img src="${model.url}" οnerrοr="imgonload(this,'${url}');" id="Image" name="model.url" >
</c:if>
</div>
</div>
<input οnchange="previewFile()" type="file" id="selImage" name="matFile" accept="image/gif,image/jpeg,image/jpg,image/png,image/bmp"/>
<input type="hidden" id="imageurl" name="url" value="<%=request.getAttribute("url")%>">
</div>
---------------------------------------异步提交-------------------------------------------
if($("#selImage").val()!=""){
if (!fileUploadValid("selImage",2)) {
return ;
}
$("#frm_add").ajaxSubmit({
type:'post',
url:'${ctx}/file/fileUpload.do',
// url:'${ctx}/contentManage/bannerManage.do?method=ajaxImage',
success:function(data){
var v= JSON.parse(data).message;
if(v!="Fail"){
$('#cover').val(v);
$.ajax({
url :"${ctx}/contentManage/bannerManage.do?method=save",
data:$("#frm_add").serialize(),
type:'post',
dataType:'text',
success:function(result){
if(result != 'fail'){
alert('保存成功');
document.location.href = "${ctx}/contentManage/bannerManage.do?method=list";
return true;
}else{
alert('banner标题重复,请重新命名');
doucment.getElementById("reTitle").value = "请重新输入标题";
return false;
}
},
error:function(){
alert('网络不好,保存失败!');
return false;
}
})
}
else {
alert('图片上传失败');
return false;
}
},
error:function(){
alert('图片上传失败!');
}
});
}else{
// $("#frm_add").submit();
// document.location.href = "${ctx}/contentManage/bannerManage.do?method=list";
$.ajax({
url :"${ctx}/contentManage/bannerManage.do?method=save",
data:$("#frm_add").serialize(),
type:'post',
dataType:'text',
success:function(result){
if(result != 'fail'){
alert('保存成功');
document.location.href = "${ctx}/contentManage/bannerManage.do?method=list";
return true;
}else{
alert('banner标题重复,请重新命名');
doucment.getElementById("reTitle").value = "请重新输入标题";
return false;
}
},
error:function(){
alert('网络不好,保存失败!');
return false;
}
});
}