springboot上传文件及文件上传限制大小异常捕获

一个简单的页面上传文件,上传的接口是/upload,请求方法是post,enctype(表单类型)是multipart/form-data 

springboot上传文件及文件上传限制大小异常捕获_第1张图片




    
    Title


在项目中新建一个webapp/uploadFile的文件夹 

springboot上传文件及文件上传限制大小异常捕获_第2张图片

接下来编写文件上传的controller接口: 

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class controller {

	SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");

	@RequestMapping("/test")

	public String test() {

		return "upload";
	}

	@PostMapping("/upload")
	@ResponseBody
	public String upload(MultipartFile uploadFile, HttpServletRequest req) {

		//获取uploadFile文件在该项目的绝对路径
		String realPath = req.getSession().getServletContext().getRealPath("/uploadFile/");
		System.out.println("realPath:" + realPath);
		String format = sdf.format(new Date());
		File folder = new File(realPath + format);
		System.out.println("folder:" + folder);
		//若果不存在该文件夹,则新建
		if (!folder.isDirectory()) {
			folder.mkdirs();
		}
		String oldName = uploadFile.getOriginalFilename();
		String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."), oldName.length());
		try {
			uploadFile.transferTo(new File(folder, newName));
			System.out.println("保存文件成功");
			String filePath = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + "/uploadFile/"
					+ format + newName;
			return filePath;
		} catch (IOException e) {
			// e.printStackTrace();
		}
		return "上传失败!";

	}
}

 

全局异常之上传文件超过了限制大小

@ControllerAdvice是最常见的全局异常处理。

@ControllerAdvice结合@ExceptionHandler客户以定义全局异常捕获机制!

import java.io.IOException;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.servlet.ModelAndView;

@ControllerAdvice
public class CustomExceptionHandler {
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public ModelAndView uploadException(MaxUploadSizeExceededException e) throws IOException {
        ModelAndView mv = new ModelAndView();
        mv.addObject("msg", "最大上传文件为1M,上传文件大小超出限制!");
        mv.setViewName("error");
        return mv;
    }

    @ExceptionHandler(Exception.class)
    public void myexce(Exception e) {
        System.out.println("myexce>>>"+e.getMessage());
    }
}

新建一个报错页面:





Insert title here

 

   

 

你可能感兴趣的:(java,Springboot,后端)