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

The following examples show how to use org.springframework.web.multipart.MultipartException. 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: ChengFeng1.5   Source File: FastDfsClientUtil.java    License: MIT License 6 votes vote down vote up
public static String uploadFiles(MultipartFile[] files){
    List<String> paths= Lists.newArrayList();
    if (files!=null&&files.length>0){
        for (int i=0;i<files.length;i++){
            if(files[i].isEmpty()){
                throw new MultipartException(ChengfengConstant.File.UPLOAD_EMPTY_ERROR);
            }
            try {
                String path = saveFile(files[i]);
                paths.add(path);
            } catch (IOException e) {
                throw new MultipartException(ChengfengConstant.File.UPLOAD_FAILURE);
            }
        }
    }
    return String.join(",",paths);//java 8
}
 
Example 2
Source Project: ChengFeng1.5   Source File: FileUploadController.java    License: MIT License 6 votes vote down vote up
@ApiOperation(value = "文件上传",notes = "批量上传文件",produces = "multipart/form-data",
        response = ResponseResult.class,httpMethod = "POST")
@PostMapping("/uploads")
@ResponseBody
public ResponseResult uploadFiles(@RequestParam("files") MultipartFile[] files){
    if(files==null||files.length<1){
        throw new MultipartException(ChengfengConstant.File.UPLOAD_EMPTY_ERROR);
    }
    try {
        StringBuffer stringBuffer=new StringBuffer();
        for (int i=0;i<files.length;i++){
            if (i!=files.length-1){
                stringBuffer.append(saveFile(files[i])).append(",");
            }else{
                stringBuffer.append(saveFile(files[i]));
            }
        }
        return ResponseResult.createBySuccess("图片上传成功",stringBuffer.toString());
    } catch (IOException e) {
        throw new MultipartException(ChengfengConstant.File.UPLOAD_FAILURE);
    }
}
 
Example 3
@Override
public InputStream getBody() throws IOException {
	if (this.multipartRequest instanceof StandardMultipartHttpServletRequest) {
		try {
			return this.multipartRequest.getPart(this.partName).getInputStream();
		}
		catch (Exception ex) {
			throw new MultipartException("Could not parse multipart servlet request", ex);
		}
	}
	else {
		MultipartFile file = this.multipartRequest.getFile(this.partName);
		if (file != null) {
			return file.getInputStream();
		}
		else {
			String paramValue = this.multipartRequest.getParameter(this.partName);
			return new ByteArrayInputStream(paramValue.getBytes(determineCharset()));
		}
	}
}
 
Example 4
@Override
public HttpHeaders getMultipartHeaders(String paramOrFileName) {
	try {
		Part part = getPart(paramOrFileName);
		if (part != null) {
			HttpHeaders headers = new HttpHeaders();
			for (String headerName : part.getHeaderNames()) {
				headers.put(headerName, new ArrayList<>(part.getHeaders(headerName)));
			}
			return headers;
		}
		else {
			return null;
		}
	}
	catch (Throwable ex) {
		throw new MultipartException("Could not access multipart servlet request", ex);
	}
}
 
Example 5
@Override
protected void handleMissingValue(String name, MethodParameter parameter, NativeWebRequest request)
		throws Exception {

	HttpServletRequest servletRequest = request.getNativeRequest(HttpServletRequest.class);
	if (MultipartResolutionDelegate.isMultipartArgument(parameter)) {
		if (servletRequest == null || !MultipartResolutionDelegate.isMultipartRequest(servletRequest)) {
			throw new MultipartException("Current request is not a multipart request");
		}
		else {
			throw new MissingServletRequestPartException(name);
		}
	}
	else {
		throw new MissingServletRequestParameterException(name,
				parameter.getNestedParameterType().getSimpleName());
	}
}
 
Example 6
Source Project: DrivingAgency   Source File: FastDfsClientUtil.java    License: MIT License 6 votes vote down vote up
public static String uploadFiles(MultipartFile[] files){
    List<String> paths= Lists.newArrayList();
    if (files!=null&&files.length>0){
        for (int i=0;i<files.length;i++){
            if(files[i].isEmpty()){
                throw new MultipartException(DrivingConstant.File.UPLOAD_EMPTY_ERROR);
            }
            try {
                String path = saveFile(files[i]);
                paths.add(path);
            } catch (IOException e) {
                throw new MultipartException(DrivingConstant.File.UPLOAD_FAILURE);
            }
        }
    }
    return String.join(",",paths);//java 8
}
 
Example 7
@Override
public InputStream getBody() throws IOException {
	if (this.multipartRequest instanceof StandardMultipartHttpServletRequest) {
		try {
			return this.multipartRequest.getPart(this.partName).getInputStream();
		}
		catch (Exception ex) {
			throw new MultipartException("Could not parse multipart servlet request", ex);
		}
	}
	else {
		MultipartFile file = this.multipartRequest.getFile(this.partName);
		if (file != null) {
			return file.getInputStream();
		}
		else {
			String paramValue = this.multipartRequest.getParameter(this.partName);
			return new ByteArrayInputStream(paramValue.getBytes(determineCharset()));
		}
	}
}
 
Example 8
@Override
public HttpHeaders getMultipartHeaders(String paramOrFileName) {
	try {
		Part part = getPart(paramOrFileName);
		if (part != null) {
			HttpHeaders headers = new HttpHeaders();
			for (String headerName : part.getHeaderNames()) {
				headers.put(headerName, new ArrayList<>(part.getHeaders(headerName)));
			}
			return headers;
		}
		else {
			return null;
		}
	}
	catch (Throwable ex) {
		throw new MultipartException("Could not access multipart servlet request", ex);
	}
}
 
Example 9
@Override
protected void handleMissingValue(String name, MethodParameter parameter, NativeWebRequest request)
		throws Exception {

	HttpServletRequest servletRequest = request.getNativeRequest(HttpServletRequest.class);
	if (MultipartResolutionDelegate.isMultipartArgument(parameter)) {
		if (servletRequest == null || !MultipartResolutionDelegate.isMultipartRequest(servletRequest)) {
			throw new MultipartException("Current request is not a multipart request");
		}
		else {
			throw new MissingServletRequestPartException(name);
		}
	}
	else {
		throw new MissingServletRequestParameterException(name,
				parameter.getNestedParameterType().getSimpleName());
	}
}
 
Example 10
@Override
public InputStream getBody() throws IOException {
	if (this.multipartRequest instanceof StandardMultipartHttpServletRequest) {
		try {
			return this.multipartRequest.getPart(this.partName).getInputStream();
		}
		catch (Exception ex) {
			throw new MultipartException("Could not parse multipart servlet request", ex);
		}
	}
	else {
		MultipartFile file = this.multipartRequest.getFile(this.partName);
		if (file != null) {
			return file.getInputStream();
		}
		else {
			String paramValue = this.multipartRequest.getParameter(this.partName);
			return new ByteArrayInputStream(paramValue.getBytes(determineEncoding()));
		}
	}
}
 
Example 11
private void parseRequest(HttpServletRequest request) {
	try {
		Collection<Part> parts = request.getParts();
		this.multipartParameterNames = new LinkedHashSet<String>(parts.size());
		MultiValueMap<String, MultipartFile> files = new LinkedMultiValueMap<String, MultipartFile>(parts.size());
		for (Part part : parts) {
			String disposition = part.getHeader(CONTENT_DISPOSITION);
			String filename = extractFilename(disposition);
			if (filename == null) {
				filename = extractFilenameWithCharset(disposition);
			}
			if (filename != null) {
				files.add(part.getName(), new StandardMultipartFile(part, filename));
			}
			else {
				this.multipartParameterNames.add(part.getName());
			}
		}
		setMultipartFiles(files);
	}
	catch (Throwable ex) {
		throw new MultipartException("Could not parse multipart servlet request", ex);
	}
}
 
Example 12
@Override
public HttpHeaders getMultipartHeaders(String paramOrFileName) {
	try {
		Part part = getPart(paramOrFileName);
		if (part != null) {
			HttpHeaders headers = new HttpHeaders();
			for (String headerName : part.getHeaderNames()) {
				headers.put(headerName, new ArrayList<String>(part.getHeaders(headerName)));
			}
			return headers;
		}
		else {
			return null;
		}
	}
	catch (Throwable ex) {
		throw new MultipartException("Could not access multipart servlet request", ex);
	}
}
 
Example 13
@Override
protected void handleMissingValue(String name, MethodParameter parameter, NativeWebRequest request)
		throws Exception {

	HttpServletRequest servletRequest = request.getNativeRequest(HttpServletRequest.class);
	if (MultipartResolutionDelegate.isMultipartArgument(parameter)) {
		if (!MultipartResolutionDelegate.isMultipartRequest(servletRequest)) {
			throw new MultipartException("Current request is not a multipart request");
		}
		else {
			throw new MissingServletRequestPartException(name);
		}
	}
	else {
		throw new MissingServletRequestParameterException(name,
				parameter.getNestedParameterType().getSimpleName());
	}
}
 
Example 14
Source Project: FastBootWeixin   Source File: WxArgumentResolver.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void handleMissingValue(String name, MethodParameter parameter, NativeWebRequest request)
        throws Exception {

    HttpServletRequest servletRequest = request.getNativeRequest(HttpServletRequest.class);
    if (MultipartResolutionDelegate.isMultipartArgument(parameter)) {
        if (!MultipartResolutionDelegate.isMultipartRequest(servletRequest)) {
            throw new MultipartException("Current request is not a multipart request");
        } else {
            throw new MissingServletRequestPartException(name);
        }
    } else {
        throw new MissingServletRequestParameterException(name,
                parameter.getNestedParameterType().getSimpleName());
    }
}
 
Example 15
@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 16
Source Project: spring4-understanding   Source File: DispatcherServlet.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Convert the request into a multipart request, and make multipart resolver available.
 * <p>If no multipart resolver is set, simply use the existing request.
 * @param request current HTTP request
 * @return the processed request (multipart wrapper if necessary)
 * @see MultipartResolver#resolveMultipart
 */
protected HttpServletRequest checkMultipart(HttpServletRequest request) throws MultipartException {
	if (this.multipartResolver != null && this.multipartResolver.isMultipart(request)) {
		if (WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class) != null) {
			logger.debug("Request is already a MultipartHttpServletRequest - if not in a forward, " +
					"this typically results from an additional MultipartFilter in web.xml");
		}
		else if (request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE) instanceof MultipartException) {
			logger.debug("Multipart resolution failed for current request before - " +
					"skipping re-resolution for undisturbed error rendering");
		}
		else {
			return this.multipartResolver.resolveMultipart(request);
		}
	}
	// If not returned before: return original request.
	return request;
}
 
Example 17
@Override
public InputStream getBody() throws IOException {
	if (this.multipartRequest instanceof StandardMultipartHttpServletRequest) {
		try {
			return this.multipartRequest.getPart(this.partName).getInputStream();
		}
		catch (Exception ex) {
			throw new MultipartException("Could not parse multipart servlet request", ex);
		}
	}
	else {
		MultipartFile file = this.multipartRequest.getFile(this.partName);
		if (file != null) {
			return file.getInputStream();
		}
		else {
			String paramValue = this.multipartRequest.getParameter(this.partName);
			return new ByteArrayInputStream(paramValue.getBytes(determineEncoding()));
		}
	}
}
 
Example 18
private void parseRequest(HttpServletRequest request) {
	try {
		Collection<Part> parts = request.getParts();
		this.multipartParameterNames = new LinkedHashSet<String>(parts.size());
		MultiValueMap<String, MultipartFile> files = new LinkedMultiValueMap<String, MultipartFile>(parts.size());
		for (Part part : parts) {
			String disposition = part.getHeader(CONTENT_DISPOSITION);
			String filename = extractFilename(disposition);
			if (filename == null) {
				filename = extractFilenameWithCharset(disposition);
			}
			if (filename != null) {
				files.add(part.getName(), new StandardMultipartFile(part, filename));
			}
			else {
				this.multipartParameterNames.add(part.getName());
			}
		}
		setMultipartFiles(files);
	}
	catch (Exception ex) {
		throw new MultipartException("Could not parse multipart servlet request", ex);
	}
}
 
Example 19
@Override
public HttpHeaders getMultipartHeaders(String paramOrFileName) {
	try {
		Part part = getPart(paramOrFileName);
		if (part != null) {
			HttpHeaders headers = new HttpHeaders();
			for (String headerName : part.getHeaderNames()) {
				headers.put(headerName, new ArrayList<String>(part.getHeaders(headerName)));
			}
			return headers;
		}
		else {
			return null;
		}
	}
	catch (Exception ex) {
		throw new MultipartException("Could not access multipart servlet request", ex);
	}
}
 
Example 20
Source Project: hawkbit   Source File: ResponseExceptionHandler.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Method for handling exception of type {@link MultipartException} which is
 * thrown in case the request body is not well formed and cannot be
 * deserialized. Called by the Spring-Framework for exception handling.
 *
 * @param request
 *            the Http request
 * @param ex
 *            the exception which occurred
 * @return the entity to be responded containing the exception information
 *         as entity.
 */
@ExceptionHandler(MultipartException.class)
public ResponseEntity<ExceptionInfo> handleMultipartException(final HttpServletRequest request,
        final Exception ex) {

    logRequest(request, ex);

    final List<Throwable> throwables = ExceptionUtils.getThrowableList(ex);
    final Throwable responseCause = Iterables.getLast(throwables);

    if (responseCause.getMessage().isEmpty()) {
        LOG.warn("Request {} lead to MultipartException without root cause message:\n{}", request.getRequestURL(),
                ex.getStackTrace());
    }

    final ExceptionInfo response = createExceptionInfo(new MultiPartFileUploadException(responseCause));
    return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
}
 
Example 21
@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 22
Source Project: AthenaServing   Source File: GlobalExceptionHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 获取全局异常
 *
 * @param request
 * @param exception
 * @return
 * @throws Exception
 */
@ExceptionHandler(value = Exception.class)
public Response allExceptionHandler(HttpServletRequest request, Exception exception) throws Exception {
    //获取请求头
    Map<String, String> headerNameMap = HttpUtil.findHeaderNameMap(request);
    String requestPath = request.getRequestURI();
    //创建返回结果
    boolean isPrint = true;
    Response<String> result;
    if (exception instanceof org.springframework.web.servlet.NoHandlerFoundException) {
        result = new Response<>(SystemErrCode.ERRCODE_NOT_FOUND_API, SystemErrCode.ERRMSG_NOT_FOUND_API);
        isPrint = false;
    } else if (exception instanceof MultipartException) {
        result = new Response<>(SystemErrCode.ERRCODE_FILE_TOO_BIG, SystemErrCode.ERRMSG_FILE_TOO_BIG);
    } else {
        result = new Response<>(SystemErrCode.ERRCODE_REQUEST_FAIL, SystemErrCode.ERRMSG_REQUEST_FAIL);
    }
    //记录错误日志
    if (isPrint) {
        String error = "";
        StackTraceElement[] trace = exception.getStackTrace();
        for (StackTraceElement s : trace) {
            error += "\tat " + s + "\r\n";
        }
        logger.error(requestPath + "\nclient header " + headerNameMap + "\nserver response " + JSON.toJSONString(result, SerializerFeature.WriteMapNullValue) + "\nerror " + error + "\n" + exception);
    } else {
        logger.error(requestPath + "\nclient header " + headerNameMap + "\nserver response " + JSON.toJSONString(result, SerializerFeature.WriteMapNullValue));
    }
    return result;
}
 
Example 23
Source Project: ChengFeng1.5   Source File: FileUploadController.java    License: MIT License 5 votes vote down vote up
@ApiOperation(value = "文件上传",notes = "上传文件",produces = "multipart/form-data",
        response = ResponseResult.class,httpMethod = "POST")
@PostMapping("/upload")
@ResponseBody
public ResponseResult uploadFile(@RequestParam("file") MultipartFile file){
    if(file.isEmpty()){
        throw new MultipartException(ChengfengConstant.File.UPLOAD_EMPTY_ERROR);
    }
    try {
        String path = saveFile(file);
        return ResponseResult.createBySuccess("图片上传成功",path);
    } catch (IOException e) {
        throw new MultipartException(ChengfengConstant.File.UPLOAD_FAILURE);
    }
}
 
Example 24
Source Project: ChengFeng1.5   Source File: ChengfengExceptionHandler.java    License: MIT License 5 votes vote down vote up
@ExceptionHandler(MultipartException.class)
public ResponseResult<Map<String,Object>> multipartExceptionHandler(MultipartException e){

    Map<String,Object> result= Maps.newHashMap();
    result.put("error", e.getMessage());

    return ResponseResult.createByError(ResponseCode.ERROR.getCode()
            ,ResponseCode.ERROR.getDesc(),result);
}
 
Example 25
Source Project: spring-analysis-note   Source File: DispatcherServlet.java    License: MIT License 5 votes vote down vote up
/**
 * Convert the request into a multipart request, and make multipart resolver available.
 * <p>If no multipart resolver is set, simply use the existing request.
 * @param request current HTTP request
 * @return the processed request (multipart wrapper if necessary)
 * @see MultipartResolver#resolveMultipart
 */
protected HttpServletRequest checkMultipart(HttpServletRequest request) throws MultipartException {
	if (this.multipartResolver != null && this.multipartResolver.isMultipart(request)) {
		if (WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class) != null) {
			if (request.getDispatcherType().equals(DispatcherType.REQUEST)) {
				logger.trace("Request already resolved to MultipartHttpServletRequest, e.g. by MultipartFilter");
			}
		}
		else if (hasMultipartException(request)) {
			logger.debug("Multipart resolution previously failed for current request - " +
					"skipping re-resolution for undisturbed error rendering");
		}
		else {
			try {
				return this.multipartResolver.resolveMultipart(request);
			}
			catch (MultipartException ex) {
				if (request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE) != null) {
					logger.debug("Multipart resolution failed for error dispatch", ex);
					// Keep processing error dispatch with regular request handle below
				}
				else {
					throw ex;
				}
			}
		}
	}
	// If not returned before: return original request.
	return request;
}
 
Example 26
Source Project: spring-analysis-note   Source File: DispatcherServlet.java    License: MIT License 5 votes vote down vote up
/**
 * Check "javax.servlet.error.exception" attribute for a multipart exception.
 */
private boolean hasMultipartException(HttpServletRequest request) {
	Throwable error = (Throwable) request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE);
	while (error != null) {
		if (error instanceof MultipartException) {
			return true;
		}
		error = error.getCause();
	}
	return false;
}
 
Example 27
/**
 * Create a new StandardMultipartHttpServletRequest wrapper for the given request.
 * @param request the servlet request to wrap
 * @param lazyParsing whether multipart parsing should be triggered lazily on
 * first access of multipart files or parameters
 * @throws MultipartException if an immediate parsing attempt failed
 * @since 3.2.9
 */
public StandardMultipartHttpServletRequest(HttpServletRequest request, boolean lazyParsing)
		throws MultipartException {

	super(request);
	if (!lazyParsing) {
		parseRequest(request);
	}
}
 
Example 28
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 29
@Override
public String getMultipartContentType(String paramOrFileName) {
	try {
		Part part = getPart(paramOrFileName);
		return (part != null ? part.getContentType() : null);
	}
	catch (Throwable ex) {
		throw new MultipartException("Could not access multipart servlet request", ex);
	}
}
 
Example 30
@Test(expected = MultipartException.class)
public void noMultipartContent() throws Exception {
	request.setMethod("POST");
	MethodParameter param = this.testMethod.annotPresent(RequestParam.class).arg(MultipartFile.class);
	resolver.resolveArgument(param, null, webRequest, null);
	fail("Expected exception: no multipart content");
}