복붙노트

[SPRING] MaxUploadSizeExceededException을 처리하는 방법

SPRING

MaxUploadSizeExceededException을 처리하는 방법

허용 된 최대 크기를 초과하는 파일을 업로드 할 때 MaxUploadSizeExceededException 예외가 나타납니다. 이 예외가 나타나면 유효성 검사 오류 메시지와 같은 오류 메시지를 표시하려고합니다. 스프링 3에서 이런 예외를 어떻게 처리 할 수 ​​있습니까?

감사.

해결법

  1. ==============================

    1.HandlerExceptionResolver를 사용하여 작동하는 솔루션을 마침내 찾아 냈습니다.

    HandlerExceptionResolver를 사용하여 작동하는 솔루션을 마침내 찾아 냈습니다.

    Spring 설정에 multipart resolver를 추가하십시오 :

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">    
       <!--  the maximum size of an uploaded file in bytes -->
       <!-- <property name="maxUploadSize" value="10000000"/> -->
       <property name="maxUploadSize" value="1000"/>
    </bean>   
    

    모델 - UploadedFile.java :

    package com.mypkg.models;
    
    import org.springframework.web.multipart.commons.CommonsMultipartFile;
    
    public class UploadedFile
    {
        private String title;
    
        private CommonsMultipartFile fileData;
    
        public String getTitle()
        {
            return title;
        }
    
        public void setTitle(String title)
        {
            this.title = title;
        }
    
        public CommonsMultipartFile getFileData()
        {
            return fileData;
        }
    
        public void setFileData(CommonsMultipartFile fileData)
        {
            this.fileData = fileData;
        }
    
    }
    

    보기 - /upload.jsp :

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
    <%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
    <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <html>
        <head>
            <title>Test File Upload</title>
        </head>
        <body>
            <h1>Select a file to upload</h1>
            <c:if test="${not empty errors}">
                <h2 style="color:red;">${errors}.</h2>
            </c:if>
            <form:form modelAttribute="uploadedFile" method="post" enctype="multipart/form-data" name="uploadedFileform" id="uploadedFileform">
                <table width="600" border="0" align="left" cellpadding="0" cellspacing="0" id="pdf_upload_form">
                    <tr>
                        <td width="180"><label class="title">Title:</label></td>
                        <td width="420"><form:input id="title" path="title" cssClass="areaInput" size="30" maxlength="128"/></td>
                    </tr>
                    <tr>
                        <td width="180"><label class="title">File:</label></td>
                        <td width="420"><form:input id="fileData" path="fileData" type="file" /></td>
                     </tr>
                     <tr>
                        <td width="180"></td>
                        <td width="420"><input type="submit" value="Upload File" /></td>
                     </tr>
                </table>
            </form:form>
        </body>
    </html>
    

    컨트롤러 - FileUploadController.java :     package com.mypkg.controllers;

    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.HashMap;
    import java.util.Map;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.validation.BindingResult;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.multipart.MaxUploadSizeExceededException;
    import org.springframework.web.servlet.HandlerExceptionResolver;
    import org.springframework.web.servlet.ModelAndView;
    
    import com.mypkg.models.UploadedFile;
    
    @Controller
    public class FileUploadController  implements HandlerExceptionResolver
    {
        @RequestMapping(value = "/upload", method = RequestMethod.GET)
        public String getUploadForm(Model model)
        {
            model.addAttribute("uploadedFile", new UploadedFile());
            return "/upload";
        }
    
        @RequestMapping(value = "/upload", method = RequestMethod.POST)
        public String create(UploadedFile uploadedFile, BindingResult result)
        {
            // Do something with the file
            System.out.println("#########  File Uploaded with Title: " + uploadedFile.getTitle());
            System.out.println("#########  Creating local file: /var/test-file-upload/" + uploadedFile.getFileData().getOriginalFilename());
    
            try
            {
    
                InputStream in = uploadedFile.getFileData().getInputStream();
                FileOutputStream f = new FileOutputStream(
                        "/var/test-file-upload/" + uploadedFile.getFileData().getOriginalFilename());
                int ch = 0;
                while ((ch = in.read()) != -1)
                {
                    f.write(ch);
                }
                f.flush();
                f.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
    
            return "redirect:/";
        }
    
        /*** Trap Exceptions during the upload and show errors back in view form ***/
        public ModelAndView resolveException(HttpServletRequest request,
                HttpServletResponse response, Object handler, Exception exception)
        {        
            Map<String, Object> model = new HashMap<String, Object>();
            if (exception instanceof MaxUploadSizeExceededException)
            {
                model.put("errors", exception.getMessage());
            } else
            {
                model.put("errors", "Unexpected error: " + exception.getMessage());
            }
            model.put("uploadedFile", new UploadedFile());
            return new ModelAndView("/upload", model);
        }
    
    }
    
    ========================================================================
    
  2. ==============================

    2.이 스티브를 해결해 주셔서 감사합니다. 나는 몇 시간 동안 풀려고 노력하는 것을 두들 겼다.

    이 스티브를 해결해 주셔서 감사합니다. 나는 몇 시간 동안 풀려고 노력하는 것을 두들 겼다.

    핵심은 컨트롤러가 HandlerExceptionResolver를 구현하고 resolveException 메소드를 추가하는 것입니다.

    --단발

  3. ==============================

    3.컨트롤러 조언 사용

    컨트롤러 조언 사용

    @ControllerAdvice
    public class GlobalExceptionHandler {
    
        @ExceptionHandler(MaxUploadSizeExceededException.class)
        public ModelAndView handleMaxUploadException(MaxUploadSizeExceededException e, HttpServletRequest request, HttpServletResponse response){
            ModelAndView mav = new ModelAndView();
            boolean isJson = request.getRequestURL().toString().contains(".json");
            if (isJson) {
                mav.setView(new MappingJacksonJsonView());
                mav.addObject("result", "nok");
            }
            else mav.setViewName("uploadError");
            return mav;
        }
    }
    
  4. ==============================

    4.ajax를 사용하는 경우 json 응답이 필요하고 resolveException 메소드에서 json 응답을 할 수 있습니다.

    ajax를 사용하는 경우 json 응답이 필요하고 resolveException 메소드에서 json 응답을 할 수 있습니다.

    @Override
      public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response,
          Object handler, Exception ex) {
        ModelAndView view = new ModelAndView();
        view.setView(new MappingJacksonJsonView());
        APIResponseData apiResponseData = new APIResponseData();
    
        if (ex instanceof MaxUploadSizeExceededException) {
          apiResponseData.markFail("error message");
          view.addObject(apiResponseData);
          return view;
        }
        return null;
      }
    
  5. from https://stackoverflow.com/questions/2689989/how-to-handle-maxuploadsizeexceededexception by cc-by-sa and MIT license