直接上源码
@Action(value = "uploadJson")
public void uploadJson() throws Exception {
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
ServletContext context = request.getServletContext();
// 文件保存目录路径
System.out.println(context.getRealPath("/"));
String savePath = context.getRealPath("/") + "/attached/";
System.out.println(savePath);
// 文件保存目录URL
String saveUrl = request.getContextPath() + "/attached/";
// 定义允许上传的文件扩展名
HashMap<String, String> extMap = new HashMap<String, String>();
extMap.put("image", "gif,jpg,jpeg,png,bmp");
// extMap.put("flash", "swf,flv");
// extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
// extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");
// 最大文件大小
long maxSize = 1000000;
response.setContentType("text/html; charset=UTF-8");
System.out.println(ServletFileUpload.isMultipartContent(request));
if (!ServletFileUpload.isMultipartContent(request)) {
getError("请选择文件。").toJson(response);
return;
}
// 检查目录
File uploadDir = new File(savePath);
if (!uploadDir.isDirectory()) {
getError("上传目录不存在。").toJson(response);
return;
}
// 检查目录写权限
if (!uploadDir.canWrite()) {
getError("上传目录没有写权限。").toJson(response);
return;
}
String dirName = request.getParameter("dir");
if (dirName == null) {
dirName = "image";
}
if (!extMap.containsKey(dirName)) {
getError("目录名不正确。").toJson(response);
return;
}
// 创建文件夹
savePath += dirName + "/";
saveUrl += dirName + "/";
File saveDirFile = new File(savePath);
if (!saveDirFile.exists()) {
saveDirFile.mkdirs();
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String ymd = sdf.format(new Date());
savePath += ymd + "/";
saveUrl += ymd + "/";
File dirFile = new File(savePath);
if (!dirFile.exists()) {
dirFile.mkdirs();
}
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
MultiPartRequestWrapper wrapper = (MultiPartRequestWrapper) request;
// 获得上传的文件名
String fileName = wrapper.getFileNames("imgFile")[0];// imgFile,imgFile,imgFile
// 获得文件过滤器
File file = wrapper.getFiles("imgFile")[0];
// 检查文件大小
if (file.length() > maxSize) {
getError("上传文件大小超过限制。").toJson(response);
return;
}
// 检查扩展名
String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
if (!Arrays.<String> asList(extMap.get(dirName).split(",")).contains(fileExt)) {
getError("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。").toJson(response);
return;
}
// 重构上传图片的名称
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "."
+ fileExt;
try {
File uploadedFile = new File(savePath, newFileName);
file.renameTo(uploadedFile);
} catch (Exception e) {
e.printStackTrace();
getError("上传文件失败。").toJson(response);
return;
}
getSuccess("上传成功").addData("url", saveUrl + newFileName).toJson(response);
}
private JsonResult getError(String message) {
JsonResult jr = new JsonResult(false,message);
jr.addData("error", 1);
return jr;
}
private JsonResult getSuccess(String message) {
JsonResult jr = new JsonResult(true, message);
jr.addData("error", 0);
return jr;
}
public class JsonResult extends HashMap<String, Object> {
/**
* 以成功标志来构造
*
* @param success
*/
public JsonResult(boolean success) {
this.put("success", success);
this.put("msg", "");
}
/**
* 以消息来构造
*
* @param msg
*/
public JsonResult(String msg) {
this.put("success", false);
this.put("msg", msg);
}
/**
* 以成功标志和消息来构造
*
* @param success
* @param msg
*/
public JsonResult(boolean success, String msg) {
this.put("success", success);
this.put("msg", msg);
}
public JsonResult addData(String name, Object value) {
this.put(name, value);
return this;
}
public String toJson() {
return JsonUtil.objectToJson(this);
}
/**
* 直接写入客户端
*
* @param response
* @throws java.io.IOException
*/
public void toJson(HttpServletResponse response) throws IOException {
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write(toJson());
}
}
public class JsonUtil {
private static final Logger logger = LoggerFactory.getLogger(JsonUtil.class);
private static final String DEFAULT_DATE_FORMAT="yyyy-MM-dd HH:mm:ss";
private static final ObjectMapper mapper;
static {
SimpleDateFormat dateFormat = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
mapper = new ObjectMapper();
mapper.setDateFormat(dateFormat);
}
public static String objectToJson(Object o) {
try {
return mapper.writeValueAsString(o);
} catch (IOException e) {
throw new RuntimeException("不能序列化对象为Json", e);
}
}
/**
* 将 json 字段串转换为 对象.
*
* @param json 字符串
* @param clazz 需要转换为的类
* @return
*/
public static <T> T json2Object(String json, Class<T> clazz) {
try {
if (StringUtils.isBlank(json)) {
return null;
}
return new ObjectMapper().readValue(json, clazz);
} catch (IOException e) {
logger.error("将 Json 转换为对象时异常,数据是:" + json);
return null;
}
}
}