/**
* 各种文件上传与判断
* types 文件类型(1图片 2视频 3文件)
*/
@RequestMapping(method = RequestMethod.POST, path = "/uploadFile")
@ResponseBody
public Object uploadFile(@RequestPart("file") MultipartFile file, Integer types) {
if (ToolUtil.isOneEmpty(file, types)) {
return ResultUtil.paramError();
}
String name = file.getOriginalFilename();
String[] fileNames = name.split("\\.");
String suffix = fileNames[fileNames.length - 1];
Boolean is = false;
if (1 == types) {
is = validateImager(suffix);
} else if (2 == types) {
is = validateVideo(suffix);
} else if (3 == types) {
is = validateFile(suffix);
}
if (!is) {
return ResultUtil.error(1, "上传文件格式错误!");
}
String fileName = UUID.randomUUID().toString() + "." + suffix;
try {
String fileSavePath = guns.getFileUploadPath();
file.transferTo(new File(fileSavePath + fileName));
} catch (Exception e) {
throw new GunsException(BizExceptionEnum.UPLOAD_ERROR);
}
Map data = new HashMap<>();
data.put("url", guns.getProjPath() + "/file/" + fileName);
data.put("fileName", fileName);
return ResultUtil.success(data);
}
//验证上传文件(图片)
public Boolean validateImager(String suffix) {
List suffixList = Arrays.asList("jpg", "png", "gif", "jpeg", "bmp");
//判断后缀格式是否正确
if (suffixList.contains(suffix)) {
return true;
} else {
return false;
}
}
//验证上传文件(视频)
public Boolean validateVideo(String suffix) {
List suffixList = Arrays.asList("avi", "wmv", "mpeg", "mp4", "mov", "mkv", "flv", "f4v", "m4v", "rmvb", "rm",
"3gp", "dat", "ts", "mts", "vob");
//判断后缀格式是否正确
if (suffixList.contains(suffix)) {
return true;
} else {
return false;
}
}
//验证上传文件(文件)
public Boolean validateFile(String suffix) {
List suffixList = Arrays.asList("css", "js", "txt");
//判断后缀格式是否正确
if (suffixList.contains(suffix)) {
return true;
} else {
return false;
}
}
/**
* 读取文件内容
*/
@RequestMapping("/{fileId:.+}")
public void renderPicture(@PathVariable("fileId") String fileId, HttpServletResponse response) {
String path = guns.getFileUploadPath() + fileId;
try {
byte[] bytes = FileUtil.toByteArray(path);
response.getOutputStream().write(bytes);//有值返回参数
} catch (Exception e) {
//如果找不到图片就返回一个默认图片
try {
response.sendRedirect("/static/imager/0.jsp");//文件不存在默认加载文件
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
原文:https://www.cnblogs.com/makedream/p/10787811.html