天天看點

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

繼續閱讀