ajax上传图片表单取消,表单提交时上传图片 表单ajax提交

页面

$(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);

}

});

})

Controller类

@RequestMapping(value = "doAdd", method = { RequestMethod.POST })

@ResponseBody

public HttpJsonResult doAdd(MultipartHttpServletRequest request, HttpServletResponse response, FbNews news){

HttpJsonResult jsonResult = new HttpJsonResult();

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 list = new ArrayList();

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;

}

原文:http://www.cnblogs.com/wenxiu/p/5367195.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值