SpringMVC框架使用jquery-form实现图片上传

1.springMV配置文件上传解析器

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" p:defaultEncoding="UTF-8">
<property name="maxUploadSize" value="2097152"/>
<property name="resolveLazily" value="true"/>
</bean>

2.引入jquery.form.js插件

注意这里img文件夹下必须要有一个文件,否则上传的图片上传不到这里,名称随意。

 

3.jsp表单数据

使用表单文件域完成文件上传<input type="file" name="xxxx">
表单必须采用POST方式提交数据,因为文件数据放置在请求体中传递,GET方式处理不了,没有请求体
文件上传采用特殊的方式传递数据,而不是普通的名值对方式,
采用多部件方式提交, 所以在表单标签中需要增加特定属性 enctype="multipart/form-data"

<form id="advertForm" method="post" action="" enctype="multipart/form-data">

<div class="form-group">
<label for="advertImgTemp">广告图片</label>
<input type="file" class="form-control" id="advpic" name="advertImgTemp" placeholder="请输入广告图片">
</div>
<button id="saveBtn" type="button" class="btn btn-success"><i class="glyphicon glyphicon-plus"></i> 新增</button>
<button type="button" class="btn btn-danger"><i class="glyphicon glyphicon-refresh"></i> 重置</button>
</form>

 4.js文件ajax异步提交

$(function(){
$("#saveBtn").click(function(){

var options = {
url:"${CWF_PATH}/advert/doAdd.do",
beforeSubmit : function(){
loadingIndex = layer.msg('数据正在保存中', {icon: 6});
return true ; //必须返回true,否则,请求终止.
},
success : function(result){
layer.close(loadingIndex);
if(result.success){
layer.msg("广告数据保存成功", {time:1000, icon:6});
window.location.href="${CWF_PATH}/advert/index.htm";
}else{
layer.msg("广告数据保存失败", {time:1000, icon:5, shift:6});
}
}
};

$("#advertForm").ajaxSubmit(options); //异步提交
return ;

});
});

4.java文件实现文件上传方法

@ResponseBody
@RequestMapping("/doAdd")
public Object doAdd(HttpServletRequest request, Advertisement advert ,HttpSession session) {
AjaxResult result = new AjaxResult();
try {
MultipartHttpServletRequest mreq = (MultipartHttpServletRequest)request;

MultipartFile mfile = mreq.getFile("advertImgTemp");//advertImgTemp是input file的name的值

String name = mfile.getOriginalFilename();//上传文件的名称
String extname = name.substring(name.lastIndexOf(".")); //取得.jpg

String imgPath = UUID.randomUUID().toString()+extname; //重新命名图片名字

ServletContext servletContext = session.getServletContext();

//realpath D:Program FilesApache Software FoundationTomcat 8.0webappscrowdfunding-mainadvert
String realpath = servletContext.getRealPath("/advert");

//path D:Program FilesApache Software FoundationTomcat 8.0webappscrowdfunding-mainadvertimg2cafef49-3827-4afe-9ff6-b89b0f931575.jpg
String path =realpath+ "\img\"+imgPath;

mfile.transferTo(new File(path)); //文件上传.

User user = (User)session.getAttribute(ConstUtil.LOGIN_USER);
advert.setUserid(user.getId());
advert.setStatus("1");
advert.setIconpath(imgPath);

advertService.addAdvert(advert);
result.setSuccess(true);
} catch ( Exception e ) {
result.setSuccess(false);
result.setMessage("上传图片失败");
e.printStackTrace();

}

return result;
}

原文地址:https://www.cnblogs.com/konglxblog/p/14108087.html