当使用Springboot自带上传时,超出最大上传限制后会返回500.
第一种处理方式,(没有成功,但能捕获到异常,无法正常显示输出信息):
通过异常捕获,问题:没有正常返回指定信息。
@RestControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
private static final Logger logger =
LoggerFactory.getLogger(GlobalExceptionHandler.class);
/**
* 处理上传异常
* @param t
* @return
*/
@ExceptionHandler(MultipartException.class)
public ResponseEntity handleAll(Throwable t) throws Exception {
// TODO do Throwable t
logger.error("=>"+t.getMessage());
HttpHeaders headers = new HttpHeaders();
headers.set("Content-Type","application/json;charset=UTF-8");
return new ResponseEntity<>(new Result(-1,"上传文件异常!",null),headers, HttpStatus.OK);
}
}
第二种处理方式可行:
如下:
先关闭启用springboot自带的上传方式enabled: false
不可同时配置 MultipartConfigElement 和 CommonsMultipartResolver
1.配置
http:
multipart:
enabled: false #默认是开启,需要关闭否则与其它上传控件冲突。
resolveLazily:true #延迟处理,并不生效
2.加入POM包依赖
commons-fileupload
commons-fileupload
1.3.1
3.配置Bean
@Configuration
public class RequestConfiguration extends WebMvcConfigurerAdapter {
@Bean
public MultipartResolver multipartResolver(){
CommonsMultipartResolver resolver = new CommonsMultipartResolver();
resolver.setDefaultEncoding("UTF-8");
//resolveLazily属性启用是为了推迟文件解析,自定义捕获文件大小异常
resolver.setResolveLazily(true);
return resolver;
}
}
4.上传处理
@RequestMapping("/upload")
@RestController
public class FilesController extends BaseController {
@Value("${upload.filePath}")
private String filePath;//文件上传路径
public String getFilePath(){
return filePath;
}
@Value("${upload.allowExt}")
private String allowExt;//允许的上传文件后缀类型
public String getAllowExt() {
return allowExt;
}
@Value("${upload.fileSize}")
private String fileSize;//允许文件上传最大限制
public String getFileSize() {
return fileSize;
}
/**
* 重命名文件
* @param fileName
* @return
*/
public String getFileName(String fileName){
if(fileName.length()>0 &&fileName.indexOf(".")>-1) {
String ext = fileName.substring(fileName.lastIndexOf("."), fileName.length());
//限定支持.jpg .png .gif .txt .pdf .doc .xls .xlsx .ppt
if(!checkExt(ext)){
return "-1";//格式错误
}
return DateUtil.getCurrentDateStr()+"_"+UtilTools.getUUID()+ext;
}
return "";
}
/**
* 判断是否在允许范围内的后缀
* @param ext
* @return
*/
public boolean checkExt(String ext){
if(ext.length()==0)return false;
String [] params = getAllowExt().split("\\|");
for (int i = 0; i < params.length; i++) {
if(params[i].equals(ext)) {
return true;
}
}
return false;
}
/**
* 导入多个文件上传
*/
@RequestMapping(value = "/uploadfiles", method = RequestMethod.POST)
public Result loadingIn(MultipartHttpServletRequest mulRequest) throws Exception {
Set> set = mulRequest.getFileMap().entrySet();
Map listFile = new LinkedHashMap<>();
//System.out.println("上传个数" + set.size());
int i = 0;
for (Map.Entry each : set) {
MultipartFile file = each.getValue();
//如果上传文件为空
if(UtilTools.isEmpty(file.getOriginalFilename())){
continue;
}
String newName = getFileName(file.getOriginalFilename());
//如果上传文件类型不允许
if(newName.equals("-1")){
return setResult("上传文件类型不支持,请检查后重新上传!");
}
//System.out.println("fileSize:"+file.getSize());
int filesize =Integer.parseInt(getFileSize());
if(file.getSize()>filesize){
return setResult("上传文件大小超出限制,最大支持"+UtilTools.fileSizeConver(filesize)+"!");
}
i++;
}
//是否存在上传文件
if(i==0){
return setResult("请选择上传文件!");
}
//进行文件上传
String filePath = mulRequest.getServletContext().getRealPath("/")+this.getFilePath();
uploadfile(filePath,listFile,set);
//System.out.println(mulRequest.getParameter("test"));//获取其它元素值
return setResult(listFile,"上传成功");
}
/**
* 进行文件上传
* @param filePath
* @param listFile
* @param set
* @throws Exception
*/
public void uploadfile(String filePath,Map listFile,Set> set) throws Exception {
for (Map.Entry each : set) {
String fileName = each.getKey();
MultipartFile file = each.getValue();
//如果上传文件为空
if(UtilTools.isEmpty(file.getOriginalFilename())){
continue;
}
String newName = getFileName(file.getOriginalFilename());
listFile.put(fileName,filePath+newName);
//重命名上传文件
IoUtil.uploadFile(file.getBytes(),filePath,newName);
}
}
/***
* 导出文件
* @param fileName
*/
@RequestMapping(value = "/downloadFile", method = RequestMethod.GET)
public void downloadFile(String filePath,String fileName,HttpServletRequest request, HttpServletResponse response){
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try{
File file = new File(filePath);
if (file.exists()) {
request.setCharacterEncoding("UTF-8");
response.setContentType("application/x-msdownload;");
//如果是空则采用原始名称
if(UtilTools.isEmpty(fileName)){
fileName = filePath.substring(filePath.lastIndexOf("/")+1,filePath.length());
}else{
if(fileName.indexOf(".")==-1){
fileName= fileName+filePath.substring(filePath.lastIndexOf("."),filePath.length());
}
}
response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("UTF-8"), "ISO8859-1"));
response.setHeader("Content-Length", String.valueOf(file.length()));
bis = new BufferedInputStream(new FileInputStream(file));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
bos.flush();
}
}catch (Exception e) {
// TODO: handle exception
System.out.println("导出文件失败!"+e.getMessage());
} finally {
try {
if (bis != null) {
bis.close();
}
if (bos != null) {
bos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}