@Controller
@RequestMapping("pic")
public class ImageUploadController {
private static final Logger logger = LoggerFactory.getLogger(ImageUploadController.class);
private static Pattern pattern = Pattern.compile("^(gif)|(jpg)|(jpeg)|(png)|(bmp)|(tif)|(tiff)$");
private static Map contentType;
static {
contentType = Maps.newConcurrentMap();
contentType.put("image/tiff", ".tif");
contentType.put("image/fax", ".fax");
contentType.put("image/gif", ".gif");
contentType.put("image/x-icon", ".ico");
contentType.put("image/jpeg", ".jpg");
contentType.put("image/pnetvue", ".net");
contentType.put("image/png", ".png");
contentType.put("image/vnd.rn-realpix", ".rp");
}
@Resource
private UploadService uploadService;
@RequestMapping(value = "/uploadImg")
@ResponseBody
public String uploadImg(@RequestParam(value = "pic", required = true) MultipartFile file) {
final long start = System.currentTimeMillis();
try {
if (file == null || file.isEmpty()) {
throw new RuntimeException("图片为空");
}
String fileName = file.getOriginalFilename();
String extension = Files.getFileExtension(fileName);
Matcher matcher = pattern.matcher(extension.toLowerCase());
boolean match = matcher.matches();
if (!match && !contentType.containsKey(file.getContentType())) {
throw new RuntimeException("图片后缀或者类型不合法");
}
if (!match) {
fileName = fileName.concat(contentType.get(file.getContentType()));
}
if (file.getBytes().length / 1024 / 1024 > 10) {
throw new RuntimeException("图片太大");
}
File imageFile = new File(request.getServletContext().getRealPath("/") + "/"
+ fileName);
FileUtils.writeByteArrayToFile(imageFile, file.getBytes());
String url = uploadService.uploadFile(imageFile, fileName);
return url;
} catch (Exception e) {
logger.error("uploadImg error ", e);
return "";
}
}
}