直接上代码~有不懂的随时欢迎
HTML页面:
<form id="ArticleForm" class="form-horizontal" method="post" enctype="multipart/form-data">
<div class="row">
<#input id='title' name='title' colNum='12' label='标题'/>
<#textarea id='content' label='内容' rows='7' maxlength='255'/>
<label>图片上传:
<input type="file" name="picture" id="file">
</label>
<div id="file_error"></div>
<label>显示类型:
<select id="flag" name="flag">
<option value="0">所有人可见</option>
<option value="1">仅自己可见</option>
</select>
</label>
<label>文章类型:
<select id="province" name="id" class="cid-select">
</select>
</label>
</div>
<div class="row btn-group-m-t">
<div class="col-sm-10">
<#button btnCss="info" name="提交" id="ensure" icon="fa-check" clickFun="ArticleInfoDlg.addSubmit()"/>
<#button btnCss="danger" name="取消" id="cancel" icon="fa-eraser" clickFun="ArticleInfoDlg.close()"/>
</div>
</div>
</form>
ajaxSubmit 的 JS:
//图片上传 及数据保存
var options = {
url: Aexit.ctxPath + "/Article/add",
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (data) {
// 如果图片上传成功则保存表单注册数据
if(data.code == 0) {
window.parent.Article.table.refresh();
ArticleInfoDlg.close();
} else {
Aexit.error(data.message);
}
}
};
// 提交表单
$('#ArticleForm').ajaxSubmit(options);
Controller接收:
private final String resourceLocation = "D://img/";
@RequestMapping(value = "/add", method = RequestMethod.POST)
@ResponseBody
public AjaxCommonObject add(HttpServletRequest request, MultipartFile picture, HttpSession session) {
String title = request.getParameter("title");
String content = request.getParameter("content");
String f = request.getParameter("flag");
String ids = request.getParameter("id");
Integer flag = Integer.parseInt(f);
Integer id = Integer.parseInt(ids);
Article dto = new Article();
AjaxCommonObject ajaxCommonObject = new AjaxCommonObject();
if (picture != null) {
String fileName = UUID.randomUUID().toString().replaceAll("-", "") + picture.getOriginalFilename().substring(picture.getOriginalFilename().lastIndexOf("."));
// 文件上传后的路径
String filePath = resourceLocation;
File dest = new File(filePath + fileName);
// 检测是否存在目录
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
picture.transferTo(dest);
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String paths = fileName;
String path = filePath + "/" + fileName;//文件路径
SysUser user = (SysUser) session.getAttribute(AuthConstants.CURRENT_USER);
Integer author = user.getId();
dto.setAuthor(author);
dto.setTitle(title);
dto.setContent(content);
dto.setFlag(flag);
Date date = new Date();
dto.setUpdatetime(date);
dto.setPicture(paths);
dto.setArticletype(id);
try {
bizService.add(dto); //返回新增记录的表id
} catch (BizCommonException e) {
return new AjaxCommonObject(e);
}
}
return ajaxCommonObject;
}