前言
用户头像的上传与下载。
配置信息
file:
# 文件保存地址
path: "/www/meeting"
picture:
# 文件格式,目前只允许jpg文件
pattern: .jpg
1、PictureUtil.java
@Component
public class PictureUtil {
@Value("${file.path}")
public String path;
@Value("${picture.pattern}")
private String filePattern;
/**
* 文件后缀名,.jpg
*/
@Autowired
private UUIDUtil uuidUtil;
/**
* 文件地址 /file/pic/{图片类型}/{uid}.jpg
* 处理图片
* @param type 类型
* @param file 图片
*/
public void handlePicture(String type, MultipartFile file, long uid)
throws IOException{
String originalName = file.getOriginalFilename();
if (originalName == null) {
throw new IllegalStateException("文件名不能为空");
}
if (!originalName.endsWith(filePattern)) {
throw new FileFormatException("不支持的文件格式");
}
// 新的文件名
String fileName = "" + uid + filePattern;
// 文件目的地址
File dest = new File(path + '/' + type + '/' + fileName);
if(!dest.getParentFile().exists()){
dest.getParentFile().mkdir();
}
file.transferTo(dest);
}
public byte[] openPicture(String filename, String type)
throws FileNotFoundException {
File source = new File(path + '/' + type + '/' + filename);
if (source.exists() && source.isFile()) {
InputStream inputStream = null;
ByteArrayOutputStream outputStream = null;
try {
inputStream = new FileInputStream(source);
outputStream = new ByteArrayOutputStream();
byte[] buff = new byte[1024];
int read = -1;
while ((read = inputStream.read(buff)) != -1) {
outputStream.write(buff, 0, read);
}
if (outputStream.size() == 0) {
throw new FileNotFoundException("空文件");
}
return outputStream.toByteArray();
} catch (IOException exception) {
return null;
} finally {
handleClose(inputStream, outputStream);
}
} else {
throw new FileNotFoundException("文件不存在");
}
}
private void handleClose(InputStream inputStream, OutputStream outputStream) {
try {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
} catch (IOException exception) {
exception.printStackTrace();
}
}
}
2、其它
前几天重新写了User类,其中profile字段变为boolean类型,表示是否采用默认头像。
在文件的上传与下载中,除了用到了PictureUtil 类,其它相较于之前的功能没有什么区别,这里就不做展示了。
然后就是在main函数所在的类里面, 添加了MultipartConfigElement的bean,用于限制文件大小。根据网上的说法,这个bean要配置在main函数所在的类里面,具体原因我不太清楚。
3、全局异常
增加了全局异常处理,留一下记录,将来使用。
@ControllerAdvice
public class GlobalExceptionHandler {
/**
* 捕获MissingServletRequestParameterException异常,400
* @param exception MissingServletRequestParameterException
* @return 400响应
*/
@ResponseBody
@ExceptionHandler(value = {MissingServletRequestParameterException.class})
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Map<String, Object> handleException(MissingServletRequestParameterException exception) {
Map<String, Object> map = new HashMap<>();
map.put("code", 400);
map.put("message", exception.getMessage());
return map;
}
/**
* 捕获MissingServletRequestParameterException异常,400
* @param exception MissingServletRequestParameterException
* @return 400响应
*/
@ResponseBody
@ExceptionHandler(value = {MissingRequestHeaderException.class})
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Map<String, Object> handleException(MissingRequestHeaderException exception) {
Map<String, Object> map = new HashMap<>();
map.put("code", 400);
map.put("message", exception.getMessage());
return map;
}
/**
* 捕获UnAuthorizedException异常,401
* @param exception UnAuthorizedException
* @return 401响应
*/
@ResponseBody
@ExceptionHandler(value = {UnAuthorizedException.class})
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public Map<String, Object> handleException(UnAuthorizedException exception) {
Map<String, Object> map = new HashMap<>();
map.put("code", 401);
map.put("message", exception.getMsg());
return map;
}
/**
* 捕获NoHandlerFoundException异常,405
* @param exception NoHandlerFoundException
* @return 404响应
*/
@ResponseBody
@ExceptionHandler(value = {NoHandlerFoundException.class})
@ResponseStatus(HttpStatus.NOT_FOUND)
public Map<String, Object> handleException(NoHandlerFoundException exception) {
Map<String, Object> map = new HashMap<>();
map.put("code", 404);
map.put("message", exception.getMessage());
return map;
}
/**
* 捕获FileNotFoundException异常,404
* @param exception FileNotFoundException
* @return 404响应
*/
@ResponseBody
@ExceptionHandler(value = {FileNotFoundException.class})
@ResponseStatus(HttpStatus.NOT_FOUND)
public Map<String, Object> handleException(FileNotFoundException exception) {
Map<String, Object> map = new HashMap<>();
map.put("code", 404);
map.put("message", exception.getMessage());
return map;
}
/**
* 捕获HttpRequestMethodNotSupportedException异常,405
* @param exception HttpRequestMethodNotSupportedException
* @return 405响应
*/
@ResponseBody
@ExceptionHandler(value = {HttpRequestMethodNotSupportedException.class})
@ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
public Map<String, Object> handleException(HttpRequestMethodNotSupportedException exception) {
Map<String, Object> map = new HashMap<>();
map.put("code", 405);
map.put("message", exception.getMessage());
return map;
}
/**
* 捕获MaxUploadSizeExceededException异常,文件大小超出上限
* @param exception MaxUploadSizeExceededException
* @return 500响应
*/
@ResponseBody
@ExceptionHandler(value = {MaxUploadSizeExceededException.class})
public Map<String, Object> handleException(MaxUploadSizeExceededException exception) {
Map<String, Object> map = new HashMap<>();
map.put("code", 500);
map.put("message", exception.getMessage());
return map;
}
/**
* 捕获其它异常
* @param exception Exception
* @return 500响应
*/
@ResponseBody
@ExceptionHandler(value = {Exception.class})
public Map<String, Object> exceptionHandler(Exception exception) {
System.out.println(exception.getMessage());
System.out.println(exception.getClass());
Map<String, Object> map = new HashMap<>();
map.put("code", 500);
map.put("message", "服务器出现异常");
return map;
}
}