Spingboot实现图片视频功能的实现
ServiceImpl
```java
@Override
public Map upload(MultipartFile multipartFileFile, HttpServletRequest request) throws IOException {
// 上传得文件类型
String fileContentType = multipartFileFile.getContentType();
// file文件路径
String filePath = ResourceUtils.getURL(ResourceUtils.URL_PROTOCOL_FILE).getPath();
// 判断当前file文件夹是否存在
File file = new File(filePath);
if (!file.exists()){
// 创建file
file.getParentFile().mkdirs();
}
String imgFilePath = filePath + "/wanrong/image/";
String videoFilePath = filePath + "/wanrong/video/";
file = new File(imgFilePath);
if (!file.exists()){
file.getParentFile().mkdirs();
}
Map<Object, Object> map = new HashMap<>();
if (StringUtils.startsWith(fileContentType,"image")){
String forImagePath = ImageUtil.saveImg(multipartFileFile, filePath, "/wanrong/image/", "/api");
map.put("imageURL",forImagePath);
} else {
map.put("key",1);
return map;
}
file = new File(videoFilePath);
if (!file.exists()){
file.getParentFile().mkdirs();
}
if (StringUtils.startsWith(fileContentType,"video")){
String videoImagePath = ImageUtil.saveImg(multipartFileFile, filePath, "/wanrong/video/", "/api");
map.put("video",videoImagePath);
} else {
map.put("key",2);
}
return map;
}
Service
Map upload(MultipartFile file, HttpServletRequest request) throws IOException;
Controller
@ApiOperation(value = "用户图片上传接口", notes = "用户图片上传接口")
@PostMapping(value = "/upload")
public Object upload(@ApiParam(value = "用户上传图片", required = true) @RequestBody MultipartFile file
, HttpServletRequest request) throws IOException {
Map map = userService.upload(file, request);
Integer isSave = (Integer) map.get("key");
if (isSave == 1 || isSave == 2){
return error(ApiErrorConstants.FILE_SAVE_ERROR);
}
return success(map);
}
错误类的定义:
```java
public static final ApiError FILE_SAVE_ERROR = new ApiError(++EXTERNAL_ERROR, "file save error");