public ModelAndView GetImage(HttpServletRequest request,
HttpServletResponse response) throws Exception {
Map<String, Object> maps = new HashMap<String, Object>();
try {
// 创建一个临时文件存放要上传的文件,第一个参数为上传文件大小,第二个参数为存放的临时目录
DiskFileItemFactory factory = new DiskFileItemFactory(
1024 * 1024 * 5, new File("D:\\temp1"));
// 设置缓冲区大小为 5M
factory.setSizeThreshold(1024 * 1024 * 5);
// 创建一个文件上传的句柄
ServletFileUpload upload = new ServletFileUpload(factory);
// 设置上传文件的整个大小和上传的单个文件大小
upload.setSizeMax(1024 * 1024 * 50);
upload.setFileSizeMax(1024 * 1024 * 5);
try {
// 把页面表单中的每一个表单元素解析成一个FileItem
List<FileItem> items = upload.parseRequest(request);
for (FileItem fileItem : items) {
// 如果是一个普通的表单元素(type不是file的表单元素)
if (fileItem.isFormField()) {
System.out.println(fileItem.getFieldName()); // 得到对应表单元素的名字
System.out.println(fileItem.getString()); // 得到表单元素的值
} else {
// 获取文件的后缀名
String fileName = fileItem.getName();// 得到文件的名字
String fileExt = fileName.substring(
fileName.lastIndexOf(".") + 1,
fileName.length());
String a = System.currentTimeMillis() + "";
String path = request.getRealPath("/") + "kmtp/"
+ "IOS" + a + ".jpg";
String url = "http://" + request.getServerName() + ":"
+ request.getServerPort() + "/"
+ request.getContextPath() + "kmtp/" + "IOS"
+ a + ".jpg";
String extension = path.substring(
path.lastIndexOf(".") + 1, path.length());
Pattern pattern = Pattern.compile("bmp|gif|gepg|png|");
Matcher matcher = pattern.matcher(extension);
if (matcher.find()) {
try {
fileItem.write(new File(path));
maps.put("message", url);
} catch (Exception e) {
e.printStackTrace();
maps.put("message", "0");
}
} else {
System.out.println("该文件类型不能够上传");
maps.put("message", "0");
}
}
}
} catch (FileUploadBase.SizeLimitExceededException e) {
System.out.println("整个请求的大小超过了规定的大小...");
maps.put("message", "0");
} catch (FileUploadBase.FileSizeLimitExceededException e) {
System.out.println("请求中一个上传文件的大小超过了规定的大小...");
maps.put("message", "0");
} catch (FileUploadException e) {
e.printStackTrace();
maps.put("message", "0");
}
} catch (Exception e) {
logger.error(e.getStackTrace());
e.printStackTrace();
maps.put("message", "0");
}
// 返回结果 0系统错误,
response.getWriter().write(
URLEncoder.encode(JSONObject.fromObject(maps).toString(),
"UTF-8"));
return null;
}