8
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Springでアップロードファイルサイズを制限する

8
Last updated at Posted at 2013-12-12

まずは、applicationContext.xmlに下記を追加する。

applicationContext.xml
<!-- enable file upload -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!-- the maximum file size in bytes -->
    <property name="maxUploadSize" value="104857600"/>
</bean>

しかし、これだけだとHTTP Status 500の「org.springframework.web.multipart.MaxUploadSizeExceededException」が発生するので、Handlerメソッドを追加してあげる必要がある。

GlobalExceptionHandler.java
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

@Component
public class GlobalExceptionHandler implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest req, HttpServletResponse resp, Object obj, Exception e)
            throws MaxUploadSizeExceededException {
        Map<String, Object> model = new HashMap<>();
        if (e instanceof MaxUploadSizeExceededException) {
            model.put("errorMsg", "Maximum upload file size is up to 100MB");
        }
        return new ModelAndView("/upload", model);
    }
}

別クラスに分けたくない場合、Uploaderのクラス内でHandlerExceptionResolverをimplementして、resolveExceptionをOverrideする方法でも可。
参照How to handle MaxUploadSizeExceededException - Stack Overflow
※ただし、上記URLではresolveExceptionメソッドに@Overrideをつけ忘れているため、そのままでは動作しない。

8
7
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?