多部分文件上载:大小超过弹出启动时的异常返回JSON错误消息

时间:2015-12-09 06:34:13

标签: spring spring-mvc spring-boot multipartform-data

由于我设置了最大文件上传限制,我正在

org.apache.tomcat.util.http.fileupload.FileUploadBase$FileSizeLimitExceededException: The field file exceeds its maximum permitted size of 2097152 bytes 
上传文件时出现

错误。我的api给出了500错误,我应该处理此错误并以JSON格式返回响应而不是ErrorController中提供的错误

我想捕获该异常,并且不是ErrorPage给予JSON响应。

@RequestMapping(value="/save",method=RequestMethod.POST)
    public ResponseDTO<String> save(@ModelAttribute @Valid FileUploadSingleDTO fileUploadSingleDTO,BindingResult bindingResult)throws MaxUploadSizeExceededException
    {
        ResponseDTO<String> result=documentDetailsService.saveDocumentSyn(fileUploadSingleDTO, bindingResult);

        return result;

    }

接受文件的DTO如下

public class FileUploadSingleDTO {
@NotNull
    private Integer documentName;

    private Integer documentVersion;

    @NotNull
    private MultipartFile file;
}

2 个答案:

答案 0 :(得分:16)

我知道你可以使用它来处理多部分文件异常。

public RectTransform recTrans;

// Use this for initialization
void Start () {
    Vector2 min = recTrans.anchorMin;
    min.x *= Screen.width;
    min.y *= Screen.height;

    min += recTrans.offsetMin;

    Vector2 max = recTrans.anchorMax;
    max.x *= Screen.width;
    max.y *= Screen.height;

    max += recTrans.offsetMax;

    Debug.Log(min + " " + max);
}

答案 1 :(得分:3)

在Controller中添加一个特殊的异常处理程序:

@ExceptionHandler(FileSizeLimitExceededException.class)
public YourReturnType uploadedAFileTooLarge(FileSizeLimitExceededException e) {
    /*...*/
}

(如果这不起作用,则必须在配置中启用异常处理。通常,Spring会默认执行此操作。)

相关问题