<form id="advertForm" method="post" action="" enctype="multipart/form-data"> <--一部分一部分提交,必须POST -->
<div class="form-group">
<label for="name">广告名称</label>
<input type="text" class="form-control" id="name" name="name" placeholder="请输入广告名称">
</div>
<div class="form-group">
<label for="url">广告地址</label>
<input type="text" class="form-control" id="url" name="url" placeholder="请输入广告地址">
</div>
<div class="form-group">
<label for="advpic">广告图片</label>
<input type="file" class="form-control" id="advpic" name="advpic" placeholder="请输入广告图片"><--图片的表单域,必须是file -->
</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>
三个必须条件:1、POST 2、form属性:enctype="multipart/form-data" 3、图片是file类型
$(function(){
$("#saveBtn").click(function(){
$("#advertForm").attr("action","${APP_PATH}/advert/doAdd.do");
$("#advertForm").submit();
});
});
@ResponseBody
@RequestMapping("/doAdd")
public Object doAdd(HttpServletRequest request, Advert advert ,HttpSession session) {
start();
try {
MultipartHttpServletRequest mreq = (MultipartHttpServletRequest)request;
MultipartFile mfile = mreq.getFile("advpic");
String name = mfile.getOriginalFilename();//java.jpg
String extname = name.substring(name.lastIndexOf(".")); // .jpg
String iconpath = UUID.randomUUID().toString()+extname; //232243343.jpg
ServletContext servletContext = session.getServletContext();
String realpath = servletContext.getRealPath("/pic");
String path =realpath+ "\\adv\\"+iconpath;
mfile.transferTo(new File(path));
User user = (User)session.getAttribute(Const.LOGIN_USER);
advert.setUserid(user.getId());
advert.setStatus("1");
advert.setIconpath(iconpath);
int count = advertService.insertAdvert(advert);
success(count==1);
} catch ( Exception e ) {
e.printStackTrace();
success(false);
}
return end();
}