spring boot 上传文件问题

spring boot 上传文件在Controller中可以捕获到异常,但是最后页面链接被重置
怎么做才能返回json数据
现在下面的配置不超过设置的大小没有问题,但是超过大小就会报错

  @Configuration //配置控制
//启用自动配置
//exclude表示自动配置时不包括Multipart配置
@EnableAutoConfiguration(exclude = {MultipartAutoConfiguration.class})
@ComponentScan //组件扫描
@ImportResource({"classpath:spring/applicationContext-mybatis.xml","classpath:spring/applicationContext-task.xml"})
public class ApplicationMain extends SpringBootServletInitializer {
    private static final Logger logger = LogManager.getLogger(ApplicationMain.class);

    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder){
        return builder.sources(ApplicationMain.class);
    }
    public static void main(String[] args)throws Exception{
        SpringApplication.run(ApplicationMain.class,args);
    }


   
    //显示声明CommonsMultipartResolver为mutipartResolver
    @Bean(name = "multipartResolver")
       public MultipartResolver multipartResolver(){
        CommonsMultipartResolver resolver = new CommonsMultipartResolver();
        resolver.setDefaultEncoding("UTF-8");
        resolver.setResolveLazily(true);//resolveLazily属性启用是为了推迟文件解析,以在在UploadAction中捕获文件大小异常
        resolver.setMaxInMemorySize(40960);
        resolver.setMaxUploadSize(50*1024*1024);//上传文件大小 50M 50*1024*1024
        return resolver;
    }   

    }

上传文件类

    
  @Controller
@RequestMapping("/file/")
public class FileUploadController {
private static final Logger logger = LogManager.getLogger(FileUploadController.class);

@Value("${sys.file.savepath}")
private String path;

@Resource
private IFileInfoService fileInfoService;

@RequestMapping(value = "upload",method = RequestMethod.GET)
public String upload(){

    return "file/upload";
}

@RequestMapping(value="upload",method = RequestMethod.POST)
@ResponseBody
public Object upload(@RequestParam("file")CommonsMultipartFile file){
    FileInfo fileInfo = new FileInfo();
    fileInfo.setContentType(file.getContentType());
    fileInfo.setCreateTime(new Date());
    fileInfo.setFilename(file.getOriginalFilename());
    fileInfo.setFilesize(file.getSize());
    if(!file.isEmpty()){
        try{
            Date date = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM");
            String dir = simpleDateFormat.format(date);
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMHHmmss");
            String disk_filename = dateFormat.format(date) + "_" + file.getOriginalFilename();

            fileInfo.setDiskDirectory(dir);
            fileInfo.setDiskFileanme(disk_filename);

            String savePath = path + "/" + dir + "/" +disk_filename;
            File saveFile = new File(savePath);
            if(!saveFile.exists()){
                FileUtils.touch(saveFile);
            }

           file.transferTo(saveFile);
        }catch (IOException e){
            logger.error(e.getMessage(),e);
        }
        fileInfoService.insert(fileInfo);
        OperateResult result = new OperateResult(ErrorCodes.ERR_CODE_SUCCESS,"上传成功");
        Map<String,Object> data = new HashMap<>();
        data.put("fileId",fileInfo.getId());
        result.setData(data);

        return result;
    }else{
        return  new OperateResult(ErrorCodes.ERR_CODE_SYSTEM,"文件不能为空");
    }

}

@ExceptionHandler({MaxUploadSizeExceededException.class})
@ResponseBody
public ModelAndView handleException(MaxUploadSizeExceededException ex, HttpServletRequest request, HttpServletResponse response){
    ModelAndView mav = new ModelAndView();
    String message =  getFileMB(((MaxUploadSizeExceededException) ex).getMaxUploadSize());
    OperateResult result = new OperateResult(ErrorCodes.ERR_CODE_SYSTEM,"文件不能大于"+message);
    if(true){
        mav.setView(new MappingJackson2JsonView());
        mav.addObject(request);
    }else{
        mav.setViewName("uploaderror");
    }
    return mav;
}

private String getFileKB(long byteFile){
    if(byteFile==0)
        return "0KB";
    long kb=1024;
    return ""+byteFile/kb+"KB";
}
private String getFileMB(long byteFile){
    if(byteFile==0)
        return "0MB";
    long mb=1024*1024;
    return ""+byteFile/mb+"MB";
}
}
阅读 24.2k
4 个回答

既然已经catch到异常了直接在catch里返回错误json不就行了,我看你那个catch里只有打印error然后没了,PS:如果用的是spring boot那个设置文件大小限制的类就不用现写成bean了,直接在application.properties里就可以配置的

异常现在可以捕获到,但是链接被拒绝,我现在没有限制大小,我后面单独写一个工程发出来,
spring boot默认的在Controller中捕获不到异常

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏