VO对象
@Data
@Accessors(chain=true)
@NoArgsConstructor
@AllArgsConstructor
public class EasyUI {
private Integer error;
private String url;
private (其余参数);
public static EasyUIImage fail() {
return new EasyUIImage(1,(url为空),(其余参数为空));
}
public static EasyUIImage success(String url,(其余参数)) {
return new EasyUIImage(0, url,(其余参数));
}
}
配置类 properties
image.fileDirPath=E:/JT_IMAGE/
image.urlPath=http://image.jt.com/
Controller对象
@RequestMapping("(url)")
public EasyUI uploadFile(MultipartFile uploadFile) {
return fileService.uploadFile(uploadFile);
}
Service对象
@Service
@PropertySource("classpath:/properties/image.properties")
public class FileServiceImpl implements FileService {
@Value("${image.fileDirPath}")
private String fileDirPath;
@Value("${image.urlPath}")
private String urlPath;
@Override
public EasyUIImage uploadFile(MultipartFile uploadFile) {
String fileName = uploadFile.getOriginalFilename();
fileName = fileName.toLowerCase();
if(!fileName.matches("^.+\\.(jpg|png|gif)$")) {
return EasyUIImage.fail();
}
try {
BufferedImage bufferedImage = ImageIO.read(uploadFile.getInputStream());
int width = bufferedImage.getWidth();
int height = bufferedImage.getHeight();
if(width ==0 || height ==0) {
return EasyUIImage.fail();
}
String datePath = new SimpleDateFormat("yyyy/MM/dd/")
.format(new Date());
String fileLocalPath = fileDirPath + datePath;
File dirFile = new File(fileLocalPath);
if (!dirFile.exists()) {
dirFile.mkdirs();
}
String uuid = UUID.randomUUID().toString().replace("-", "");
int index = fileName.lastIndexOf(".");
String fileType = fileName.substring(index);
String realFileName = uuid + fileType;
String realFilePath = fileLocalPath + realFileName;
uploadFile.transferTo(new File(realFilePath));
String url = urlPath + datePath + realFileName;
return EasyUIImage.success(url, width, height);
} catch (Exception e) {
e.printStackTrace();
return EasyUIImage.fail();
}
}
}