页面
<script type="text/javascript" src="js/jquery.form.js"></script>
<script language="javascript">
$(function() {
//提交表单
$("#add").click(function() {
if($(‘#addForm‘).form(‘validate‘)){
var options = {
url: ‘${currentBaseUrl}/doAdd‘,
type: ‘post‘,
success: function (data) {
if("ok"==data.message)
window.location.href=data.backUrl;
else{
$.messager.alert(‘提示‘, data.message);
$("#imageFile").val("").focus()
}
}
};
$(‘#addForm‘).ajaxSubmit(options);
}
});
})
</script>
<form method="post" class="validForm" id="addForm" name="addForm" enctype="multipart/form-data">
<input type="file" id="imageFile" name="imageFile" class="txt w240 easyui-validatebox" />
<input type="button" id="add" class="btn" value="提交" />
</form>
Controller类
@RequestMapping(value = "doAdd", method = { RequestMethod.POST })
@ResponseBody
public HttpJsonResult<Object> doAdd(MultipartHttpServletRequest request, HttpServletResponse response, FbNews news){
HttpJsonResult<Object> jsonResult = new HttpJsonResult<Object>();
try {
MultipartFile multipartFile = request.getFile("imageFile");
if (null != multipartFile && multipartFile.getSize() > 0) {
//扩展名
String extend = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf(".") + 1).toLowerCase();
if (!isImg(extend)) {
jsonResult.setMessage("请上传图片!");
return jsonResult;
}
File tmpFile = new File(buildImgPath(request) + "/"+ multipartFile.getOriginalFilename());
if (!multipartFile.isEmpty()) {
byte[] bytes = multipartFile.getBytes();
BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(tmpFile));
stream.write(bytes);
stream.close();
}
}
/**其他代码省略**/
jsonResult.setMessage("ok");
//添加成功 返回列表页面
jsonResult.setBackUrl(DomainUrlUtil.getJM_URL_RESOURCES() + "/admin/fbfc/news");
return jsonResult;
} catch (Exception e) {
throw new RuntimeException();
}
}
//是否是图片
private boolean isImg(String extend) {
List<String> list = new ArrayList<String>();
list.add("jpg");
list.add("jpeg");
list.add("bmp");
list.add("gif");
list.add("png");
list.add("tif");
return list.contains(extend);
}
//图片上传的路径
private String buildImgPath(HttpServletRequest request) {
String path = "upload";
SimpleDateFormat formater = new SimpleDateFormat("yyyyMMdd");
path += "/" + formater.format(new Date());
path = request.getRealPath(path);
File dir = new File(path);
if (!dir.exists()) {
try {
dir.mkdirs();
} catch (Exception e) {
log.error("error", e);
}
}
return path;
}