org.springframework.web.multipart.MaxUploadSizeExceededException Java Examples

The following examples show how to use org.springframework.web.multipart.MaxUploadSizeExceededException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ExceptionHandler.java    From yfs with Apache License 2.0 6 votes vote down vote up
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
                                     Exception ex) {
    ModelAndView mv = new ModelAndView();
    MappingJackson2JsonView view = new MappingJackson2JsonView();
    Map<String, Object> attributes = new HashMap();
    if (ex instanceof MaxUploadSizeExceededException) {
        attributes.put("code", ResultCode.C403.code);
        attributes.put("msg", "Maximum upload size of " + ((MaxUploadSizeExceededException) ex).getMaxUploadSize() + " bytes exceeded");
        logger.warn(ex.getMessage());
    } else {
        attributes.put("code", ResultCode.C500.code);
        attributes.put("msg", ResultCode.C500.desc);
        logger.error("Internal server error", ex);
    }
    view.setAttributesMap(attributes);
    mv.setView(view);
    return mv;
}
 
Example #2
Source File: ExceptionHandler.java    From opencron with Apache License 2.0 6 votes vote down vote up
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception ex) {
	if (ex instanceof MaxUploadSizeExceededException) {
		WebUtils.writeJson(httpServletResponse,"长传的文件大小超过"+((MaxUploadSizeExceededException)ex).getMaxUploadSize() + "字节限制,上传失败!");
		return null;
	}
	ModelAndView view = new ModelAndView();

	ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
	ex.printStackTrace(new PrintStream(byteArrayOutputStream));
	String exception = byteArrayOutputStream.toString();

	view.getModel().put("error","URL:"+ WebUtils.getWebUrlPath(httpServletRequest)+httpServletRequest.getRequestURI()+"\r\n\r\nERROR:"+exception);
	logger.error("[opencron]error:{}",ex.getLocalizedMessage());
	view.setViewName("/error/500");
	return view;
}
 
Example #3
Source File: UploadFilter.java    From qconfig with MIT License 6 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    try {
        String ip = RequestUtil.getRealIP(req);
        String rtxId = AdminConstants.CLIENT_UPLOAD_USERNAME;
        userContext.setIp(ip);
        userContext.setAccount(new Account(rtxId));
        MDC.put(MdcConstants.USER_ID, rtxId);
        MDC.put(MdcConstants.IP, ip);

        chain.doFilter(request, response);
    } catch (ServletException e) {
        if (e.getCause() instanceof MaxUploadSizeExceededException) {
            request.getRequestDispatcher("/api/config/uploadError.do").forward(request, response);
        } else {
            throw e;
        }
    } finally {
        userContext.clear();
        MDC.remove(MdcConstants.USER_ID);
        MDC.remove(MdcConstants.IP);
    }
}
 
Example #4
Source File: UploadValidateInterceptor.java    From onetwo with Apache License 2.0 6 votes vote down vote up
protected void checkFileTypes(List<MultipartFile> fileItems, UploadFileValidator validator){
		List<String> allowed = validator!=null?Arrays.asList(validator.allowedPostfix()):Arrays.asList(DEFAULT_ALLOW_FILE_TYPES);
		
		for(MultipartFile item : fileItems){
			String postfix = FileUtils.getExtendName(item.getOriginalFilename().toLowerCase().trim());//trim防止后缀加空格绕过检查
			
			if(validator==null){
				if(!allowed.contains(postfix))
					throw new ServiceException("It's not allowed file type. file: " + item.getOriginalFilename(), UplaodErrorCode.NOT_ALLOW_FILE);
			}else{
				if(!allowed.contains(postfix))
					throw new ServiceException(validator.allowedPostfixErrorMessage() + " file: " + item.getOriginalFilename(), UplaodErrorCode.NOT_ALLOW_FILE);
				if(item.getSize()>validator.maxUploadSize())
					throw new MaxUploadSizeExceededException(validator.maxUploadSize());
			}
//				throw new MaxUploadSizeExceededException(validator.maxUploadSize());
		}
	}
 
Example #5
Source File: ComplexPortletApplicationContext.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
public MultipartActionRequest resolveMultipart(ActionRequest request) throws MultipartException {
	if (request.getAttribute("fail") != null) {
		throw new MaxUploadSizeExceededException(1000);
	}
	if (request instanceof MultipartActionRequest) {
		throw new IllegalStateException("Already a multipart request");
	}
	if (request.getAttribute("resolved") != null) {
		throw new IllegalStateException("Already resolved");
	}
	request.setAttribute("resolved", Boolean.TRUE);
	MultiValueMap<String, MultipartFile> files = new LinkedMultiValueMap<String, MultipartFile>();
	files.set("someFile", new MockMultipartFile("someFile", "someContent".getBytes()));
	Map<String, String[]> params = new HashMap<String, String[]>();
	params.put("someParam", new String[] {"someParam"});
	return new DefaultMultipartActionRequest(request, files, params, Collections.<String, String>emptyMap());
}
 
Example #6
Source File: DispatcherServletTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void multipartResolutionFailed() throws Exception {
	MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/locale.do;abc=def");
	request.addPreferredLocale(Locale.CANADA);
	request.addUserRole("role1");
	request.setAttribute("fail", Boolean.TRUE);
	MockHttpServletResponse response = new MockHttpServletResponse();
	complexDispatcherServlet.service(request, response);
	assertTrue("forwarded to failed", "failed0.jsp".equals(response.getForwardedUrl()));
	assertEquals(200, response.getStatus());
	assertTrue("correct exception", request.getAttribute(
			SimpleMappingExceptionResolver.DEFAULT_EXCEPTION_ATTRIBUTE) instanceof MaxUploadSizeExceededException);
}
 
Example #7
Source File: ControllerTimeAdvice.java    From AthenaServing with Apache License 2.0 5 votes vote down vote up
/**
 * 环绕通知
 *
 * @param pjp
 * @return
 * @throws Throwable
 */
@Around("execution(* com.iflytek.ccr.polaris.cynosure.controller..*.*(..)))")
public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
    //记录开始时间
    long startTimeMillis = System.currentTimeMillis();

    RequestAttributes ra = RequestContextHolder.getRequestAttributes();
    ServletRequestAttributes sra = (ServletRequestAttributes) ra;
    HttpServletRequest request = sra.getRequest();
    //获取请求头
    Map<String, String> headerNameMap = HttpUtil.findHeaderNameMap(request);
    String requestPath = request.getRequestURI();

    //获取请求参数
    String params = this.getParams(pjp);

    // result的值就是被拦截方法的返回值
    Object result;
    try {
        result = pjp.proceed();
        long endTimeMillis = System.currentTimeMillis();
        logger.info(requestPath + " cost time " + (endTimeMillis - startTimeMillis) + "ms" + "\nclient header " + headerNameMap + "\nclient request " + params + "\nserver response " + JSON.toJSONString(result, SerializerFeature.WriteMapNullValue));
    } catch (Exception ex) {
        if (ex instanceof MaxUploadSizeExceededException) {
            result = new Response<String>(SystemErrCode.ERRCODE_FILE_TOO_BIG, SystemErrCode.ERRMSG_FILE_TOO_BIG);
        } else {
            result = new Response<String>(SystemErrCode.ERRCODE_REQUEST_FAIL, SystemErrCode.ERRMSG_REQUEST_FAIL);
        }
        String error = "";
        StackTraceElement[] trace = ex.getStackTrace();
        for (StackTraceElement s : trace) {
            error += "\tat " + s + "\r\n";
        }
        //记录错误日志
        logger.error(requestPath + "\nclient header " + headerNameMap + "\nclient request " + params + "\nserver response " + JSON.toJSONString(result, SerializerFeature.WriteMapNullValue) + "\nerror " + error + "\n" + ex);
    }
    return result;
}
 
Example #8
Source File: ExceptionHandleController.java    From OneBlog with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Shiro权限认证异常
 *
 * @param e
 * @return
 */
@ExceptionHandler(value = {MaxUploadSizeExceededException.class})
@ResponseBody
public ResponseVO maxUploadSizeExceededExceptionHandle(Throwable e) {
    e.printStackTrace(); // 打印异常栈
    return ResultUtil.error(CommonConst.DEFAULT_ERROR_CODE, ResponseStatus.UPLOAD_FILE_ERROR.getMessage() + "文件过大!");
}
 
Example #9
Source File: ExceptionHandler.java    From JobX with Apache License 2.0 5 votes vote down vote up
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception ex) {
    if (ex instanceof MaxUploadSizeExceededException) {
        WebUtils.writeJson(httpServletResponse, "长传的文件大小超过" + ((MaxUploadSizeExceededException) ex).getMaxUploadSize() + "字节限制,上传失败!");
        return null;
    }
    ModelAndView view = new ModelAndView();

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    ex.printStackTrace(new PrintStream(byteArrayOutputStream));
    String exception = byteArrayOutputStream.toString();

    view.getModel().put("error", "URL:" + WebUtils.getWebUrlPath(httpServletRequest) + httpServletRequest.getRequestURI() + "\r\n\r\nERROR:" + exception);
    logger.error("[JobX]error:{}", ex.getLocalizedMessage());
    view.setViewName("/error/500");
    return view;
}
 
Example #10
Source File: DispatcherPortletTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void multipartResolutionFailed() throws Exception {
	MockActionRequest request = new MockActionRequest();
	MockActionResponse response = new MockActionResponse();
	request.setPortletMode(PortletMode.EDIT);
	request.addUserRole("role1");
	request.setAttribute("fail", Boolean.TRUE);
	complexDispatcherPortlet.processAction(request, response);
	String exception = response.getRenderParameter(DispatcherPortlet.ACTION_EXCEPTION_RENDER_PARAMETER);
	assertTrue(exception.startsWith(MaxUploadSizeExceededException.class.getName()));
}
 
Example #11
Source File: RestExceptionHandlerAdvice.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
@ResponseStatus(HttpStatus.REQUEST_ENTITY_TOO_LARGE) // 413
@ExceptionHandler(MaxUploadSizeExceededException.class)
@ResponseBody
public ErrorInfo handleMaxFileSizeExceeded(MaxUploadSizeExceededException musee) {
  ErrorInfo errorInfo = new ErrorInfo("Maximum upload size exceeded");
  User currentUser = SecurityUtils.getCurrentUserObject();

  // TODO: SPECIFIC MESSAGE OPENS SOURCE?
  errorInfo.setMessageKey(UPLOAD_LIMIT_EXCEEDED_TRIAL_USER);
  errorInfo.addParameter("quota", musee.getMaxUploadSize());
  return errorInfo;
}
 
Example #12
Source File: TgolHandlerExceptionResolver.java    From Asqatasun with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * This exception resolver displays the audit set page for file upload
 * when the MaxUploadSizeExceededException is thrown
 *
 * @param hsr
 * @param hsr1
 * @param o
 * @param excptn
 * @return
 */
@Override
@SuppressWarnings("unchecked")
public ModelAndView doResolveException(HttpServletRequest hsr, HttpServletResponse hsr1, Object o, Exception excptn) {
    if (excptn instanceof MaxUploadSizeExceededException) {
        Map<String, String> model = new HashMap<String, String>();
        model.put(TgolKeyStore.CONTRACT_ID_KEY, hsr.getParameter(TgolKeyStore.CONTRACT_ID_KEY));
        return new ModelAndView(TgolKeyStore.MAX_FILE_SIZE_ERROR_VIEW_NAME, model);
    }
    return super.doResolveException(hsr, hsr1, o, excptn);
}
 
Example #13
Source File: BootStandardServletMultipartResolver.java    From onetwo with Apache License 2.0 5 votes vote down vote up
@Override
public MultipartHttpServletRequest resolveMultipart(HttpServletRequest request) throws MultipartException {
	if(maxUploadSize>=0){
		long requestSize = RequestUtils.getContentLength(request);
		if(requestSize!=-1 && requestSize>maxUploadSize){
			throw new MaxUploadSizeExceededException(maxUploadSize);
		}
	}
	try {
		return super.resolveMultipart(request);
	} catch (MultipartException e) {
		FileSizeLimitExceededException fsee = LangUtils.getCauseException(e, FileSizeLimitExceededException.class);
		if (fsee!=null) {
			throw new UploadFileSizeLimitExceededException(fsee);
		} else {
			throw new BaseException(WebErrors.UPLOAD, e);
		}
	}
}
 
Example #14
Source File: SpringMultipartFilterProxy.java    From onetwo with Apache License 2.0 5 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
		throws ServletException, IOException {
	try {
		super.doFilterInternal(request, response, filterChain);
	} catch (MaxUploadSizeExceededException e) {
		handleMaxUploadSizeExceededException(request, response, e);
	}
}
 
Example #15
Source File: CosMultipartResolver.java    From Lottery with GNU General Public License v2.0 5 votes vote down vote up
public MultipartHttpServletRequest resolveMultipart(
		HttpServletRequest request) throws MultipartException {
	try {
		CosMultipartRequest multipartRequest = newMultipartRequest(request);
		if (logger.isDebugEnabled()) {
			Set<String> fileNames = multipartRequest.getFileNames();
			for (String fileName : fileNames) {
				File file = multipartRequest.getFile(fileName);
				logger.debug("Found multipart file '"
						+ fileName
						+ "' of size "
						+ (file != null ? file.length() : 0)
						+ " bytes with original filename ["
						+ multipartRequest.getOriginalFileName(fileName)
						+ "]"
						+ (file != null ? "stored at ["
								+ file.getAbsolutePath() + "]" : "empty"));
			}
		}
		return new CosMultipartHttpServletRequest(request, multipartRequest);
	} catch (IOException ex) {
		// Unfortunately, COS always throws an IOException,
		// so we need to check the error message here!
		if (ex.getMessage().indexOf("exceeds limit") != -1) {
			throw new MaxUploadSizeExceededException(this.maxUploadSize, ex);
		} else {
			throw new MultipartException(
					"Could not parse multipart request", ex);
		}
	}
}
 
Example #16
Source File: SpringExceptionHandler.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@ExceptionHandler(MaxUploadSizeExceededException.class)
public final Object handleSpringPayloadTooLargeException(
    Exception e, HttpServletRequest request) {
  Exception cause = e;
  while (cause.getCause() instanceof Exception) {
    cause = (Exception) cause.getCause();
  }
  return logAndHandleException(cause, PAYLOAD_TOO_LARGE, request);
}
 
Example #17
Source File: FileUploadController.java    From tutorials with MIT License 5 votes vote down vote up
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object object, Exception exc) {
    ModelAndView modelAndView = new ModelAndView("file");
    if (exc instanceof MaxUploadSizeExceededException) {
        modelAndView.getModel()
            .put("message", "File size exceeds limit!");
    }
    return modelAndView;
}
 
Example #18
Source File: FileUploadController.java    From tutorials with MIT License 5 votes vote down vote up
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object object, Exception exc) {        
    ModelAndView modelAndView = new ModelAndView("file");
    if (exc instanceof MaxUploadSizeExceededException) {
        modelAndView.getModel().put("message", "File size exceeds limit!");
    }
    return modelAndView;
}
 
Example #19
Source File: MultipartWebErrorHandler.java    From errors-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
@NonNull
@Override
public HandledException handle(Throwable exception) {
    String errorCode = MULTIPART_EXPECTED;
    Map<String, List<Argument>> arguments = emptyMap();

    if (exception instanceof MaxUploadSizeExceededException) {
        long maxSize = ((MaxUploadSizeExceededException) exception).getMaxUploadSize();
        errorCode = MAX_SIZE;
        arguments = singletonMap(MAX_SIZE, singletonList(arg("max_size", maxSize)));
    }

    return new HandledException(errorCode, BAD_REQUEST, arguments);
}
 
Example #20
Source File: TensorBootController.java    From tensorboot with Apache License 2.0 5 votes vote down vote up
@ExceptionHandler(RuntimeException.class)
public ModelAndView doResolveException(RuntimeException e) {
    if (e instanceof MaxUploadSizeExceededException) {
        return getModelAndView("uploadForm", "File is too large");
    } else if (e instanceof ConstraintViolationException) {
        return getModelAndView("uploadForm", "Malformed request: " + e.getMessage());
    } else if (e instanceof ServiceException) {
        log.info("Error during processing request", e);
        return getModelAndView("uploadForm", e.getMessage());
    } else {
        log.info("Error during processing request", e);
        return getModelAndView("error", "Internal server error");
    }
}
 
Example #21
Source File: RestControllerAdviceHandler.java    From nimrod with MIT License 5 votes vote down vote up
@ExceptionHandler(MultipartException.class)
public ResponseEntity<FailureEntity> sizeLimitExceededExceptionHandler(HttpServletRequest httpServletRequest, Throwable throwable) {
    HttpStatus httpStatus = getStatus(httpServletRequest);
    FailureEntity fm = failureEntity.i18n("file.upload_fail");
    if (throwable instanceof MaxUploadSizeExceededException) {
        String maxFileSize = DataSizeUtil.pretty(DataSize.parse((String) dictionaryService.get("FILE", "MAX_FILE_SIZE")).toBytes());
        String maxRequestSize = DataSizeUtil.pretty(DataSize.parse((String) dictionaryService.get("FILE", "MAX_REQUEST_SIZE")).toBytes());
        fm = failureEntity.i18n("file.upload_fail_max_upload_size_exceeded", maxFileSize, maxRequestSize);
    }
    throwable.printStackTrace();
    return new ResponseEntity<>(fm, httpStatus);
}
 
Example #22
Source File: GlobalExceptionHand.java    From spring-boot-shiro with Apache License 2.0 5 votes vote down vote up
/**
 * 422 - UNPROCESSABLE_ENTITY
 */
@ResponseStatus(HttpStatus.UNPROCESSABLE_ENTITY)
@ExceptionHandler(MaxUploadSizeExceededException.class)
public Response handleMaxUploadSizeExceededException(Exception e) {
    String msg = "所上传文件大小超过最大限制,上传失败!";
    log.error(msg, e);
    return new Response().failure(msg);
}
 
Example #23
Source File: RepeatableReadAuthorizationFilter.java    From qconfig with MIT License 5 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    try {
        super.doFilter(request, response, chain);
    } catch (ServletException e) {
        if (e.getCause() instanceof MaxUploadSizeExceededException) {
            response.setContentType("application/json");
            response.setCharacterEncoding("utf8");
            response.getWriter().println("{\"message\":\"文件不能超过" + AdminConstants.MAX_FILE_SIZE_IN_K + "k\",\"data\":null,\"status\":1}");
        } else {
            throw e;
        }
    }
}
 
Example #24
Source File: StandardMultipartHttpServletRequest.java    From java-technology-stack with MIT License 5 votes vote down vote up
protected void handleParseFailure(Throwable ex) {
	String msg = ex.getMessage();
	if (msg != null && msg.contains("size") && msg.contains("exceed")) {
		throw new MaxUploadSizeExceededException(-1, ex);
	}
	throw new MultipartException("Failed to parse multipart servlet request", ex);
}
 
Example #25
Source File: DispatcherServletTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void multipartResolutionFailed() throws Exception {
	MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/locale.do;abc=def");
	request.addPreferredLocale(Locale.CANADA);
	request.addUserRole("role1");
	request.setAttribute("fail", Boolean.TRUE);
	MockHttpServletResponse response = new MockHttpServletResponse();
	complexDispatcherServlet.service(request, response);
	assertTrue("forwarded to failed", "failed0.jsp".equals(response.getForwardedUrl()));
	assertEquals(200, response.getStatus());
	assertTrue("correct exception", request.getAttribute(
			SimpleMappingExceptionResolver.DEFAULT_EXCEPTION_ATTRIBUTE) instanceof MaxUploadSizeExceededException);
}
 
Example #26
Source File: DispatcherServletTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void multipartResolutionFailed() throws Exception {
	MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/locale.do;abc=def");
	request.addPreferredLocale(Locale.CANADA);
	request.addUserRole("role1");
	request.setAttribute("fail", Boolean.TRUE);
	MockHttpServletResponse response = new MockHttpServletResponse();
	complexDispatcherServlet.service(request, response);
	assertTrue("forwarded to failed", "failed0.jsp".equals(response.getForwardedUrl()));
	assertEquals(200, response.getStatus());
	assertTrue("correct exception", request.getAttribute(
			SimpleMappingExceptionResolver.DEFAULT_EXCEPTION_ATTRIBUTE) instanceof MaxUploadSizeExceededException);
}
 
Example #27
Source File: ExceptionAdvice.java    From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@ExceptionHandler(MaxUploadSizeExceededException.class)
@ResponseStatus(PAYLOAD_TOO_LARGE)
@ResponseBody
public JsonObject maxUploadSizeExceededException(MaxUploadSizeExceededException e) {
    return makeMsg(format("Upload file size is limit to %s.", fileSizeLimit));
}
 
Example #28
Source File: TensorBootRestController.java    From tensorboot with Apache License 2.0 4 votes vote down vote up
@ExceptionHandler(MaxUploadSizeExceededException.class)
public ServiceError handleMaxUploadSizeExceededException(MaxUploadSizeExceededException exc) {
    log.info("Error during processing request", exc);
    return new ServiceError("File is too large");
}
 
Example #29
Source File: FileUploadExceptionAdvice.java    From tutorials with MIT License 4 votes vote down vote up
@ExceptionHandler(MaxUploadSizeExceededException.class)
public ModelAndView handleMaxSizeException(MaxUploadSizeExceededException exc, HttpServletRequest request, HttpServletResponse response){
    ModelAndView modelAndView = new ModelAndView("file");
    modelAndView.getModel().put("message", "File too large!");
    return modelAndView;
}
 
Example #30
Source File: FileUploadExceptionAdvice.java    From tutorials with MIT License 4 votes vote down vote up
@ExceptionHandler(MaxUploadSizeExceededException.class)
public ModelAndView handleMaxSizeException(MaxUploadSizeExceededException exc, HttpServletRequest request, HttpServletResponse response){
    ModelAndView modelAndView = new ModelAndView("file");
    modelAndView.getModel().put("message", "File too large!");
    return modelAndView;
}