packagewebapp.controller;importcom.alibaba.fastjson.JSONObject;importcom.baomidou.mybatisplus.core.toolkit.StringUtils;importorg.apache.commons.io.FileUtils;importorg.springframework.context.annotation.Scope;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RequestParam;importorg.springframework.web.bind.annotation.ResponseBody;importorg.springframework.web.bind.annotation.RestController;importorg.springframework.web.multipart.MultipartFile;importjavax.servlet.http.HttpServletResponse;importjava.io.File;importjava.io.IOException;importjava.io.PrintWriter;importjava.util.HashMap;importjava.util.Map;importjava.util.UUID;
@Scope("prototype")
@RestControllerpublic classFileController {//图片在服务器所在路径
private static String WEB_BASE_PATH = "/var/xxx";//图片前缀域名(需搭建文件服务器)
private static String WEB_PIC_HOST = "http://pic.xxx.com/";//ckeditor图片上传
@RequestMapping("uploadCkEditor")
@ResponseBodypublic void uploadWangEdit(@RequestParam("upload") MultipartFile file, HttpServletResponse response) {
FileResponse fileResponse= newFileResponse();try{
PrintWriter out=response.getWriter();if(file.isEmpty()) {
String error= fileResponse.error(0, "文件为空");
out.println(error);
}
String filePath=WEB_BASE_PATH;
File dir= newFile(filePath);if(!dir.exists()) {
dir.mkdir();
}
String orgName=file.getOriginalFilename();
String[] split= orgName.split("\\.");
String suffix= split[1];//检查图片格式
boolean imgTypeIsRight =checkImgType(suffix);if (!imgTypeIsRight){
String error= fileResponse.error(0, "无效状态异常");
out.println(error);
}
String fileName= UUID.randomUUID().toString() +"."+suffix;
String path= filePath +fileName;
File tempFile= null;try{
tempFile= newFile(path);
FileUtils.copyInputStreamToFile(file.getInputStream(), tempFile);
}catch(IllegalStateException e) {
String error= fileResponse.error(0, "无效状态异常");
out.println(error);return;
}catch(IOException e) {
String error= fileResponse.error(0, "IO异常");
out.println(error);return;
}
String success= fileResponse.success(1, fileName, WEB_PIC_HOST+fileName, "");
out.print(success);
}catch(IOException ex){return;
}
}//ckEditor图片上传响应体
public class FileResponse extends HashMap{
Map msgMap = new HashMap<>();public String error(intcode, String msg){
FileResponse result= newFileResponse();
msgMap.put("message",msg);
result.put("uploaded",code);
result.put("error",msgMap);returnJSONObject.toJSON(result).toString();
}public String success(intcode, String fileName,String url,String msg){
FileResponse result= newFileResponse();if(!StringUtils.isEmpty(msg)){
msgMap.put("message",msg);
result.put("error",msgMap);
}
result.put("uploaded",code);
result.put("fileName",fileName);
result.put("url",url);returnJSONObject.toJSON(result).toString();
}
}//检查图片格式
private booleancheckImgType(String suffix){if (!"jpg".equals(suffix)&&!"jpeg".equals(suffix)&&!"png".equals(suffix)&&!"gif".equals(suffix)){return false;
}else{return true;
}
}
}