Springboot 文件的上传下载及异常的全局处理

1.属性配置
注意一点 当value注入时如果只是一个单词的时候 不带点. 注入报异常;不能正常注入

#最大文件大小。值可以使用后缀“MB”或“KB”。指示兆字节或千字节大小。
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
#自定义上传文件保存的路径
upload.file=D:/testUpload/

2.文件上传下载controller

@RestController
public class FileUpDownloadController {

    @Value("${upload.file}")
    private String uploadPath;
    @PostMapping("/upload")
    public AjaxResponse uploadFile(@RequestParam("filename")MultipartFile file){

        //文件不为空
        if(file.isEmpty()){
            return AjaxResponse.fail("请选择一个要上传的文件!");
        }
        //文件名字
        String filename = file.getOriginalFilename();
        long fileSize = file.getSize();
        log.info("文件名:"+filename+" 文件大小:"+fileSize);
        File dest = new File(uploadPath + filename);
        //文件不存在新建路径
        if (!dest.getParentFile().exists()){
            dest.getParentFile().mkdir();
        }
        try {
            //转存文件
            file.transferTo(dest);
            return AjaxResponse.success("文件上传成功!");
        } catch (IOException e) {

            e.printStackTrace();
            return AjaxResponse.fail("文件上传失败!");
        }
    }

    @GetMapping("/download/{filename}")
    public AjaxResponse downLoadFile(HttpServletResponse response, @PathVariable(value = "filename")String filename){
        File dest = new File(uploadPath + filename);
        try (FileInputStream inputStream = new FileInputStream(dest)) {
            // 设置被下载而不是被打开
            response.setContentType("application/gorce-download");
            // 设置被第三方工具打开,设置下载的文件名
            response.addHeader("Content-disposition","attachment;fileName="+filename);

            ServletOutputStream responseOutputStream = response.getOutputStream();
            byte[] bytes = new byte[1024];
            int len=0;
            while ((len=inputStream.read(bytes))!=-1){
                responseOutputStream.write(bytes,0,len);
            }
            return AjaxResponse.success("下载成功!");
        }catch (Exception e){
            return AjaxResponse.fail("下载失败!");
        }
    }
}

3.全局异常处理类

@RestControllerAdvice
public class CustomExceptionCatch {

    @Value("${spring.servlet.multipart.max-file-size}")
    private String fileMax;

    @ExceptionHandler(value = MaxUploadSizeExceededException.class)
    public AjaxResponse fileMax(MaxUploadSizeExceededException e){
//        e.printStackTrace();
        return AjaxResponse.fail("上传文件超过限制大小"+fileMax);
    }
    @ExceptionHandler(value = ArithmeticException.class)
    public AjaxResponse fileMax(ArithmeticException e){
        return AjaxResponse.fail(e.getMessage());
    }
    @ExceptionHandler(value = Exception.class)
    public AjaxResponse fileMax(Exception e){
        e.printStackTrace();
        return AjaxResponse.fail(e.getMessage());
    }
}
发布了17 篇原创文章 · 获赞 1 · 访问量 565

猜你喜欢

转载自blog.csdn.net/a393007511/article/details/102854387