参考
commons-fileupload
commons-fileupload
1.2.2
$(function() {
$("#merSave").validate({
rules: {
/*,
attachment:{
required: true,
filetype:["jpg","png"]
}*/,
},
messages: {
/*,
attachment:{
filetype: messagesFomat( "只能上传jpg、png图片")
}*/
},
submitHandler: function(form) {
// 商户附件,企业商户必填
var attachment = $("#attachment").val();
if(mer_target=="-1" || mer_target=="0"){
if(attachment==null || attachment==""){
$.messager.alert("提示", "企业商户上传附件不能为空!", "error");
return;
}
}
if(attachment!=null&&attachment!=""){
var file_name_index = attachment.lastIndexOf(".");
var file_name_suffix = attachment.substr(file_name_index).toLowerCase();
if(file_name_suffix==".jpg"||file_name_suffix==".png"){
}else{
$.messager.alert("提示", "附件格式为jpg、png!", "error");
return ;
}
}
$.messager.confirm("提示", "是否确认保存该信息?", function(r) {
if (r) {
load();
$(form).ajaxSubmit(function(data) {
disLoad();
if (data.flag == 0) {
$.messager.alert("提示", "保存成功!", "info", function() {
var url = ctx()+"/mer/merQuery";
location.href = url;
});
} else {
$.messager.alert("提示", data.errorMessage, "error");
}
});
}
});
}
});
});
package com.cxy.utils;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;
import com.app.biz.controller.BaseController;
public class MultipartFileUtils {
public static final String FILESAVEPATH1="C:\\fileSource\\gameIco";//游戏图标保存路径
public static final String FILESAVEPATH2="C:\\fileSource\\gameImg";//游戏海报保存地址
public static final String FILESAVEPATH3="C:\\fileSource\\gamApk";//游戏文件保存路径
public static final String MUSICSAVEPATH1="C:\\fileSource\\musicImg";//音乐海报保存路径
public static final String MUSICSAVEPATH2="/uploadFile/musicFilePath";//音乐文件保存地址
public static final String BOOKSAVEPATH1="C:\\fileSource\\bookImg";//图书海报保存路径
public static final String BOOKSAVEPATH2="/uploadFile/bookFilePath";//图书文件保存地址
public static Map saveToTomcat(HttpServletRequest request,
MultipartFile attachment, String PRODUCT_IMG_SAVE_PATH) {
String parentPath = request.getSession().getServletContext()
.getRealPath(java.io.File.separator);// tomcat的webapp前缀
String originalFilename = attachment.getOriginalFilename();// 图片原名.png
String fileNameSuffix = originalFilename.substring(originalFilename
.lastIndexOf("."));// .png
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
String fileName = BaseController.uuid()+fileNameSuffix;// 新的图片名称.png
Map saveResult = MultipartFileUtils.saveFileToDisk(
parentPath, PRODUCT_IMG_SAVE_PATH, fileName, attachment,
800 * 1024 * 1024L,request);
if (!"0".equals(saveResult.get("status").toString())) {
// 保存失败
return BaseController.outData("0001", saveResult.get("msg")
.toString(), null);
}
String save_path = (String) saveResult.get("save_path");// 保存的路径名
saveResult.get("old_name");// 上传时的文件名 QQ图片20161226133411.png}
return BaseController.outData("0000", save_path, null);
}
public static Map saveToDisk(HttpServletRequest request,
MultipartFile attachment, String PRODUCT_IMG_SAVE_PATH) {
String originalFilename = attachment.getOriginalFilename();// 图片原名.png
String fileNameSuffix = originalFilename.substring(originalFilename
.lastIndexOf("."));// .png
String fileName = BaseController.uuid()+fileNameSuffix;// 新的图片名称.png
Map saveResult = MultipartFileUtils.saveFileToDisk(
"", PRODUCT_IMG_SAVE_PATH, fileName, attachment,
800 * 1024 * 1024L,request);
if (!"0".equals(saveResult.get("status").toString())) {
// 保存失败
return BaseController.outData("0001", saveResult.get("msg")
.toString(), null);
}
String save_path = (String) saveResult.get("save_path");// 保存的路径名
saveResult.get("old_name");// 上传时的文件名 QQ图片20161226133411.png}
return BaseController.outData("0000", save_path, null);
}
/**
* @param request
* @param fileUrl 删除的文件路径
* @throws IOException
*/
public static void deleteOld(HttpServletRequest request,
String fileUrl) throws IOException {
// String parentPath = request.getSession().getServletContext()
// .getRealPath(File.separator);
String url = fileUrl;
File file = new File(url);
if(!file.isDirectory()){
if (file.exists()) {
file.delete();
}
}else {//是文件夹则删除路径下的所有文件夹
FileUtils.deleteDirectory(file);
}
}
/**
* 保存文件到磁盘
*/
private static Map saveFileToDisk(String parentPath,
String PRODUCT_IMG_SAVE_PATH, String fileName, MultipartFile file, long maxSize,HttpServletRequest request) {
Map result = new HashMap();
if (file == null || file.isEmpty() || file.getSize() <= 0) {
result.put("status", "1");
result.put("msg", "文件为空");
return result;
}
// 检查文件大小,800M
if (file.getSize() > maxSize) {
result.put("status", "1");
result.put("msg", "文件过大");
return result;
}
try {
int endIndex = 0;
// String parentPathUrl = parentPath.getPath();
// endIndex = parentPathUrl.indexOf(BaseController.getProjectName(request));
// System.out.println(parentPathUrl.substring(0, endIndex));
// String savePath = parentPathUrl.substring(0, endIndex);
String filePath = parentPath+ PRODUCT_IMG_SAVE_PATH + "/"
+ fileName;// D:\workspace\sms_boss\src\main\webapp\\sms_check_file\passway\sign_20170302062136381.png
System.out.println(filePath);
File saveDir = new File(filePath);
if (saveDir.isFile() && saveDir.exists()) {
result.put("status", "1");
result.put("msg", "文件名重复");
return result;
}
if (!saveDir.getParentFile().exists()) {
saveDir.getParentFile().mkdirs();
}
System.out.println("save path ... : " + saveDir.getPath());
// 转存文件
file.transferTo(saveDir);
System.out.println("save file success : " + saveDir.getPath());
result.put("status", "0");
result.put("save_path", PRODUCT_IMG_SAVE_PATH + "/"
+ fileName);// 保存的路径名
// \sms_check_file\passway\sign_20170302063551308.png
result.put("old_name", file.getOriginalFilename());// 上传时的文件名
// QQ图片20161226133411.png
return result;
} catch (Exception e) {
e.printStackTrace();
result.put("status", "1");
result.put("msg", "保存失败");
return result;
}
}
}
package com.app.biz.controller;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.ehcache.CacheManager;
import org.springframework.beans.factory.annotation.Autowired;
/**
* 提供获取request,session,转换json等常用方法
*
* @author dj
*
*/
public class BaseController {
// header 常量定义
private static final String DEFAULT_ENCODING = "utf-8";
private static final boolean DEFAULT_NOCACHE = true;
// Content Type 常量定义
public static final String TEXT_TYPE = "text/plain";
public static final String JSON_TYPE = "application/json";
public static final String XML_TYPE = "text/xml";
public static final String HTML_TYPE = "text/html";
public static final String JS_TYPE = "text/javascript";
public static final String EXCEL_TYPE = "application/vnd.ms-excel";
public static int PAGE_NUMERIC = 20;
/**
* 直接输出内容的简便函数.
*/
public static void render(final String contentType, final String content,
final HttpServletResponse response) {
HttpServletResponse resp = initResponseHeader(contentType, response);
try {
resp.getWriter().write(content);
resp.getWriter().flush();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 直接输出文本.
*/
protected void outText(final String text, final HttpServletResponse response) {
render(TEXT_TYPE, text, response);
}
/**
* 直接输出HTML.
*/
protected void outHtml(final String html, final HttpServletResponse response) {
render(HTML_TYPE, html, response);
}
/**
* 直接输出XML.
*/
protected void outXml(final String xml, final HttpServletResponse response) {
render(XML_TYPE, xml, response);
}
/**
* 输出JSON,可以接收参数如: [{'name':'www'},{'name':'www'}],['a','b'],new
* String[]{'a','b'},合并如下:jsonString = "{TOTALCOUNT:" + totalCount + ",
* ROOT:" + jsonString + "}";
*
* @param jsonString
* json字符串.
*
*/
public static void outJson(final String json, final HttpServletResponse response) {
render(JSON_TYPE, json, response);
}
/**
* 设置让浏览器弹出下载对话框的Header.
*
* @param fileName
* 下载后的文件名.
*/
protected void setFileDownloadHeader(HttpServletResponse response,
String fileName) {
try {
// 中文文件名支持
String encodedfileName = new String(fileName.getBytes(),
"ISO8859-1");
response.setHeader("Content-Disposition", "attachment; filename=\""
+ encodedfileName + "\"");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 分析并设置contentType与headers.
*/
protected static HttpServletResponse initResponseHeader(final String contentType,
final HttpServletResponse response) {
// 分析headers参数
String encoding = DEFAULT_ENCODING;
boolean noCache = DEFAULT_NOCACHE;
// 设置headers参数
String fullContentType = contentType + ";charset=" + encoding;
response.setContentType(fullContentType);
if (noCache) {
setNoCacheHeader(response);
}
return response;
}
/**
* 设置客户端无缓存Header.
*/
protected static void setNoCacheHeader(HttpServletResponse response) {
// Http 1.0 header
response.setDateHeader("Expires", 0);
response.addHeader("Pragma", "no-cache");
// Http 1.1 header
response.setHeader("Cache-Control", "no-cache");
}
/*
protected void outJsonMap(int flag, String errorMessage, HttpServletResponse response){
Map jsonMap = new HashMap();
jsonMap.put("flag", flag);
jsonMap.put("errorMessage", errorMessage);
String json = JSONObject.fromObject(jsonMap).toString();
outJson(json, response);
}*/
public static Map outData(String code,String message,Object object){
Map jsonMap = new HashMap();
jsonMap.put("code", code);
jsonMap.put("msg", message);
jsonMap.put("data", object);
return jsonMap;
}
//java中遍历实体类,获取属性名和属性值
public static Map testReflect(Object model) throws Exception{
Map map=new HashMap();
for (Field field : model.getClass().getDeclaredFields()) {
field.setAccessible(true);
map.put(field.getName(), field.get(model));
/*System.out.println(field.getName() + ":" + field.get(model) );*/
}
return map;
}
/**
* 封装JDK自带的UUID, 通过Random数字生成, 中间无-分割.
*/
public static String uuid() {
return UUID.randomUUID().toString().replaceAll("-", "");
}
/** tomcat的webapp前缀
* @param request
* @return
*/
public static String getTomcatPath(HttpServletRequest request){
String parentPath = request.getSession().getServletContext()
.getRealPath(java.io.File.separator);
return parentPath;
}
}
6.controller
@RequestMapping(value="/insertOrUpdate")
@ResponseBody
public int insertOrUpdate(BizBookMsg msg,HttpServletRequest request,
@RequestParam(value = "bookImg", required = false) MultipartFile bookImg) throws Exception{
int i =0;
i = bookMsgSer.insertOrUpdate(msg,request,bookImg);
return i;
}