Java Code Examples for org.springframework.web.multipart.MaxUploadSizeExceededException

The following examples show how to use org.springframework.web.multipart.MaxUploadSizeExceededException. These examples are extracted from open source projects. 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 Project: qconfig   Source File: UploadFilter.java    License: 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 2
Source Project: yfs   Source File: ExceptionHandler.java    License: 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 3
Source Project: opencron   Source File: ExceptionHandler.java    License: 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 4
@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 5
Source Project: onetwo   Source File: UploadValidateInterceptor.java    License: 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 6
@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 7
Source Project: AthenaServing   Source File: ControllerTimeAdvice.java    License: 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 Project: tensorboot   Source File: TensorBootController.java    License: 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 9
Source Project: spring-boot-shiro   Source File: GlobalExceptionHand.java    License: 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 10
Source Project: spring-analysis-note   Source File: DispatcherServletTests.java    License: 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 11
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 12
Source Project: java-technology-stack   Source File: DispatcherServletTests.java    License: 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 13
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 14
Source Project: qconfig   Source File: RepeatableReadAuthorizationFilter.java    License: 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 15
Source Project: nimrod   Source File: RestControllerAdviceHandler.java    License: 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 16
@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 17
@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 18
/**
 * 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 19
Source Project: JobX   Source File: ExceptionHandler.java    License: 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 20
@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 21
@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 22
/**
 * 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 23
Source Project: onetwo   Source File: SpringMultipartFilterProxy.java    License: 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 24
Source Project: Lottery   Source File: CosMultipartResolver.java    License: 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 25
@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 26
Source Project: tutorials   Source File: FileUploadController.java    License: 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 27
Source Project: tutorials   Source File: FileUploadController.java    License: 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 28
Source Project: tensorboot   Source File: TensorBootRestController.java    License: 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 Project: jeecg-cloud   Source File: JeecgBootExceptionHandler.java    License: Apache License 2.0 4 votes vote down vote up
/** 
* spring默认上传大小100MB 超出大小捕获异常MaxUploadSizeExceededException 
*/
 @ExceptionHandler(MaxUploadSizeExceededException.class)
 public Result<?> handleMaxUploadSizeExceededException(MaxUploadSizeExceededException e) {
 	log.error(e.getMessage(), e);
     return Result.error("文件大小超出10MB限制, 请压缩或降低文件质量! ");
 }
 
Example 30
/** 
* spring默认上传大小100MB 超出大小捕获异常MaxUploadSizeExceededException 
*/
 @ExceptionHandler(MaxUploadSizeExceededException.class)
 public Result<?> handleMaxUploadSizeExceededException(MaxUploadSizeExceededException e) {
 	log.error(e.getMessage(), e);
     return Result.error("文件大小超出10MB限制, 请压缩或降低文件质量! ");
 }