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

The following examples show how to use org.springframework.web.multipart.MultipartHttpServletRequest. 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: wangmarket   Source File: AttachmentFile.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * SpringMVC 上传文件,配置允许上传的文件后缀再 systemConfig.xml 的AttachmentFile节点
 * @param filePath 上传后的文件所在的目录、路径,如 "jar/file/"
 * @param request SpringMVC接收的 {@link MultipartFile},若是有上传文件,会自动转化为{@link MultipartFile}保存
 * @param formFileName form表单上传的单个文件,表单里上传文件的文件名
 * @return {@link UploadFileVO} 若成功,则上传了文件并且上传成功
 */
public static UploadFileVO uploadFile(String filePath,HttpServletRequest request,String formFileName) {
	UploadFileVO uploadFileVO = new UploadFileVO();
	if (request instanceof MultipartHttpServletRequest) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;  
		List<MultipartFile> list = multipartRequest.getFiles(formFileName);  
		if(list.size()>0 && !list.get(0).isEmpty()){
			MultipartFile multi = list.get(0);
			uploadFileVO = uploadFileByMultipartFile(filePath, multi);
		}else{
			uploadFileVO.setResult(UploadFileVO.NOTFILE);
			uploadFileVO.setInfo(Language.show("oss_uploadNotFile"));
		}
    }else{
    	uploadFileVO.setResult(UploadFileVO.NOTFILE);
		uploadFileVO.setInfo(Language.show("oss_uploadNotFile"));
    }
	return uploadFileVO;
}
 
Example 2
Source Project: AlgoTrader   Source File: GrailsDataBinder.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void bindWithRequestAndPropertyValues(ServletRequest request, MutablePropertyValues mpvs) {
	GrailsWebRequest webRequest = GrailsWebRequest.lookup((HttpServletRequest) request);
	if (webRequest != null) {
		final ApplicationContext applicationContext = webRequest.getApplicationContext();
		if (applicationContext != null) {
			final Map<String, BindEventListener> bindEventListenerMap = applicationContext.getBeansOfType(BindEventListener.class);
			for (BindEventListener bindEventListener : bindEventListenerMap.values()) {
				bindEventListener.doBind(getTarget(), mpvs, getTypeConverter());
			}
		}
	}
	preProcessMutablePropertyValues(mpvs);

	if (request instanceof MultipartHttpServletRequest) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		bindMultipart(multipartRequest.getMultiFileMap(), mpvs);
	}
	doBind(mpvs);
}
 
Example 3
@Override
public void cleanupMultipart(MultipartHttpServletRequest request) {
	if (!(request instanceof AbstractMultipartHttpServletRequest) ||
			((AbstractMultipartHttpServletRequest) request).isResolved()) {
		// To be on the safe side: explicitly delete the parts,
		// but only actual file parts (for Resin compatibility)
		try {
			for (Part part : request.getParts()) {
				if (request.getFile(part.getName()) != null) {
					part.delete();
				}
			}
		}
		catch (Throwable ex) {
			LogFactory.getLog(getClass()).warn("Failed to perform cleanup of multipart items", ex);
		}
	}
}
 
Example 4
@Override
public List<String> uploadForAddress(Long projectId, HttpServletRequest request) {
    List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
    if (!(files != null && !files.isEmpty())) {
        throw new CommonException("error.attachment.exits");
    }
    List<String> result = new ArrayList<>();
    for (MultipartFile multipartFile : files) {
        String fileName = multipartFile.getOriginalFilename();
        ResponseEntity<String> response = fileFeignClient.uploadFile(BACKETNAME, fileName, multipartFile);
        if (response == null || response.getStatusCode() != HttpStatus.OK) {
            throw new CommonException("error.attachment.upload");
        }
        result.add(attachmentUrl + "/" + BACKETNAME + "/" + dealUrl(response.getBody()));
    }
    return result;
}
 
Example 5
/**
 * Create a new instance.
 * @param request the current request
 * @param partName the name of the part to adapt to the {@link ServerHttpRequest} contract
 * @throws MissingServletRequestPartException if the request part cannot be found
 * @throws IllegalArgumentException if MultipartHttpServletRequest cannot be initialized
 */
public RequestPartServletServerHttpRequest(HttpServletRequest request, String partName)
		throws MissingServletRequestPartException {

	super(request);

	this.multipartRequest = asMultipartRequest(request);
	this.partName = partName;

	this.headers = this.multipartRequest.getMultipartHeaders(this.partName);
	if (this.headers == null) {
		if (request instanceof MultipartHttpServletRequest) {
			throw new MissingServletRequestPartException(partName);
		}
		else {
			throw new IllegalArgumentException(
					"Failed to obtain request part: " + partName + ". " +
					"The part is missing or multipart processing is not configured. " +
					"Check for a MultipartResolver bean or if Servlet 3.0 multipart processing is enabled.");
		}
	}
}
 
Example 6
Source Project: jeecg-cloud   Source File: SysUploadController.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 上传
 * @param request
 */
@PostMapping(value = "/uploadMinio")
public Result<?> uploadMinio(HttpServletRequest request) {
    Result<?> result = new Result<>();
    String bizPath = request.getParameter("biz");
    if(oConvertUtils.isEmpty(bizPath)){
        bizPath = "";
    }
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    MultipartFile file = multipartRequest.getFile("file");// 获取上传文件对象
    String orgName = file.getOriginalFilename();// 获取文件名
    orgName = CommonUtils.getFileName(orgName);
    String file_url =  MinioUtil.upload(file,bizPath);
    //保存文件信息
    OSSFile minioFile = new OSSFile();
    minioFile.setFileName(orgName);
    minioFile.setUrl(file_url);
    ossFileService.save(minioFile);
    result.setMessage(file_url);
    result.setSuccess(true);
    return result;
}
 
Example 7
Source Project: charging_pile_cloud   Source File: FileUploadController.java    License: MIT License 6 votes vote down vote up
/**
 * 阿里云上传图片接口
 *
 * @param request
 * @param response
 * @return
 */

@RequestMapping(value = "uploadAliOss", method = RequestMethod.POST)
@ResponseBody
@ApiOperation(notes = "上传图片", value = "上传图片")
public Map<String, Object> uploadAliOss(HttpServletRequest request, HttpServletResponse response) {
    MultipartHttpServletRequest mhs = (MultipartHttpServletRequest) request;

    MultipartFile file = mhs.getFile("file");
    try {
        String fileName = FileUpload.getFileName(file);
        if (StringUtils.isBlank(fileName)) {
            throw new CommonException("未知的文件格式");
        }
        String url = OSSInterface.uploadImage(file.getOriginalFilename(), file.getInputStream(), OSSFather.bucketName_user);
        if(com.util.StringUtils.isBlank(url)){
            return ResponseUtil.getNotNormalMap(ResponseMsg.UPLOAD_FAIL);
        }else {
            return ResponseUtil.getSuccessNoMsg(url);
        }
    } catch (IOException e) {
        throw new CommonException("图片上传失败");
    }
}
 
Example 8
@Override
public List<String> uploadForAddress(Long projectId, HttpServletRequest request) {
    List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
    if (!(files != null && !files.isEmpty())) {
        throw new CommonException("error.attachment.exits");
    }
    List<String> result = new ArrayList<>();
    for (MultipartFile multipartFile : files) {
        String fileName = multipartFile.getOriginalFilename();
        ResponseEntity<String> response = fileFeignClient.uploadFile(BACKETNAME, fileName, multipartFile);
        if (response == null || response.getStatusCode() != HttpStatus.OK) {
            throw new CommonException("error.attachment.upload");
        }
        result.add(attachmentUrl + "/" + BACKETNAME + "/" + dealUrl(response.getBody()));
    }
    return result;
}
 
Example 9
Source Project: jeewx   Source File: JeecgBlobDataController.java    License: Apache License 2.0 6 votes vote down vote up
@RequestMapping(params = "upload")
@ResponseBody
   public AjaxJson upload(HttpServletRequest request, String documentTitle, HttpServletResponse response) {
	AjaxJson j = new AjaxJson();
	
	MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
	Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
	for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
		MultipartFile file = entity.getValue();// 获取上传文件对象
		try {
			jeecgBlobDataService.saveObj(documentTitle, file);
			j.setMsg("文件导入成功!");
		} catch (Exception e) {
			j.setMsg("文件导入失败!");
			logger.error(ExceptionUtil.getExceptionMessage(e));
		}
		//break; // 不支持多个文件导入?
	}

	return j;
   }
 
Example 10
Source Project: hdw-dubbo   Source File: UploadInterceptor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
    boolean flag=true;
    List<String> suffixList = interceptorProperties.getUpload().getAllowFileExtensions();

    if (request instanceof MultipartHttpServletRequest) {
        AtomicBoolean suffixFlag= new AtomicBoolean(true);
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> files = multipartRequest.getFileMap();
        files.entrySet().forEach((entry) -> {
            MultipartFile multipartFile = entry.getValue();
            String fileName = multipartFile.getOriginalFilename();
            System.out.println("fileName:" + fileName);
            suffixFlag.set(checkFile(fileName, suffixList));
        });
        flag=suffixFlag.get();
    }
    return flag;
}
 
Example 11
Source Project: wangmarket   Source File: AttachmentFile.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * SpringMVC 上传图片文件,配置允许上传的文件后缀再 systemConfig.xml 的AttachmentFile节点
 * @param filePath 上传后的文件所在的目录、路径,如 "jar/file/"
 * @param request SpringMVC接收的 {@link MultipartFile},若是有上传图片文件,会自动转化为{@link MultipartFile}保存
 * @param formFileName form表单上传的单个图片文件,表单里上传文件的文件名
 * @param maxWidth 上传图片的最大宽度,若超过这个宽度,会对图片进行等比缩放为当前宽度。
 * @return {@link UploadFileVO} 若成功,则上传了文件并且上传成功
 */
public static UploadFileVO uploadImage(String filePath,HttpServletRequest request,String formFileName, int maxWidth) {
	UploadFileVO uploadFileVO = new UploadFileVO();
	if (request instanceof MultipartHttpServletRequest) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;  
		List<MultipartFile> imageList = multipartRequest.getFiles(formFileName);  
		if(imageList.size()>0 && !imageList.get(0).isEmpty()){
			MultipartFile multi = imageList.get(0);
			uploadFileVO = uploadImageByMultipartFile(filePath, multi, maxWidth);
		}else{
			uploadFileVO.setResult(UploadFileVO.NOTFILE);
			uploadFileVO.setInfo(Language.show("oss_uploadNotFile"));
		}
    }else{
    	uploadFileVO.setResult(UploadFileVO.NOTFILE);
		uploadFileVO.setInfo(Language.show("oss_uploadNotFile"));
    }
	return uploadFileVO;
}
 
Example 12
Source Project: jeewx   Source File: QywxGzuserinfoController.java    License: Apache License 2.0 6 votes vote down vote up
/**
	 * 编辑
	 * @return
	 */
	@RequestMapping(params = "doEdit",method ={RequestMethod.GET, RequestMethod.POST})
	@ResponseBody
	public AjaxJson doEdit(HttpServletRequest request ,@ModelAttribute QywxGzuserinfo qywxGzuserinfo){
		AjaxJson j = new AjaxJson();
		try {
			//1.1身份认证信息(微信号/手机/邮箱)不能同时为空
			if(StringUtils.isBlank(qywxGzuserinfo.getWeixinid()) && StringUtils.isBlank(qywxGzuserinfo.getMobile()) && StringUtils.isBlank(qywxGzuserinfo.getEmail())){
				throw new Exception("微信号/手机/邮箱 不能同时为空");
			}
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		    MultipartFile uploadfile = multipartRequest.getFile("avatar_file");
//			qywxGzuserinfoDao.update(qywxGzuserinfo);
			qywxGzuserinfoService.updateGzuserinfo(qywxGzuserinfo,uploadfile,request);
			j.setMsg("编辑成功");
		} catch (Exception e) {
		    log.info(e.getMessage());
			j.setSuccess(false);
			j.setMsg("编辑失败,详细原因:"+e.getMessage());
		}
		return j;
	}
 
Example 13
Source Project: teaching   Source File: SysUploadController.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 上传
 * @param request
 */
@PostMapping(value = "/uploadMinio")
public Result<?> uploadMinio(HttpServletRequest request) {
    Result<?> result = new Result<>();
    String bizPath = request.getParameter("biz");
    if(oConvertUtils.isEmpty(bizPath)){
        bizPath = "";
    }
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    MultipartFile file = multipartRequest.getFile("file");// 获取上传文件对象
    String orgName = file.getOriginalFilename();// 获取文件名
    String file_url =  MinioUtil.upload(file,bizPath);
    //保存文件信息
    OSSFile minioFile = new OSSFile();
    minioFile.setFileName(orgName);
    minioFile.setUrl(file_url);
    ossFileService.save(minioFile);
    result.setMessage(file_url);
    result.setSuccess(true);
    return result;
}
 
Example 14
Source Project: oslits   Source File: Adm2000Controller.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * 사용자 정보가 기록된 엑셀파일 업로드 처리
 * 엑셀의 사용자 정보 리스트 전달
 * @param
 * @return
 * @exception Exception
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
@RequestMapping(value="/adm/adm2000/adm2000/excelUpload.do" ,method = RequestMethod.POST)
public ModelAndView uploadExcelParseToAjax(final MultipartHttpServletRequest multiRequest,  HttpServletResponse response ) throws Exception {
	List<Object> excelList =null;
	Map jsonMap =new HashMap();

	Map<String, MultipartFile> fileMap = multiRequest.getFileMap();
	try{
		Set<Entry<String,  MultipartFile>> entrySet = fileMap.entrySet();
		Class clz = Adm2000VO.class;
		
		for (Entry<String,  MultipartFile> entry : entrySet) {
			SheetParser parser = new SheetParser(entry.getValue().getInputStream(),1);
			excelList = parser.createEntity(clz, 1);
		}
	}
	catch(Exception ex){
		Log.error("selectExcelUploadView()", ex);
		throw new Exception(ex.getMessage());
	}

	jsonMap.put("parseList", excelList);
	return  new ModelAndView("jsonView",jsonMap);
}
 
Example 15
Source Project: jeewx-boot   Source File: JwSystemProjectController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 保存图片
 * @return
 */
@RequestMapping(value = "/doUpload",method ={RequestMethod.POST})
@ResponseBody
public AjaxJson doUpload(MultipartHttpServletRequest request,HttpServletResponse response){
	AjaxJson j = new AjaxJson();
	try {
		MultipartFile uploadify = request.getFile("file");
        /*byte[] bytes = uploadify.getBytes();
        //String uploadDir = ContextHolderUtils.getRequest().getSession().getServletContext().getRealPath("upload/img/system");

		String uploadDir = upLoadPath + "/upload/img/system";
        File dirPath = new File(uploadDir);  
        if (!dirPath.exists()) {
            dirPath.mkdirs();  
        }  
        String sep = System.getProperty("file.separator");  
        File uploadedFile = new File(uploadDir + sep  
                + uploadify.getOriginalFilename());  
        FileCopyUtils.copy(bytes, uploadedFile);  
        //update-begin--Author:zhangweijian  Date: 20181205 for:返回文件名
        j.setObj(uploadify.getOriginalFilename());
        //update-end--Author:zhangweijian  Date: 20181205 for:返回文件名*/
		// 高依赖版本 oss 上传工具
		String filename = OSSBootUtil.upload(uploadify , "upload/img/system");
		j.setObj(filename);
		j.setMsg("保存成功");
	} catch (Exception e) {
		j.setSuccess(false);
		j.setMsg("保存失败");
	}
	return j;
}
 
Example 16
Source Project: gocd   Source File: ArtifactsControllerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnBadRequestIfRequiredHeadersAreMissingOnACreateArtifactRequest() throws Exception {
    MultipartHttpServletRequest multipartHttpServletRequest = new MockMultipartHttpServletRequest();

    when(systemEnvironment.isApiSafeModeEnabled()).thenReturn(true);
    ModelAndView modelAndView = artifactsController.postArtifact("pipeline", "invalid-label", "stage", "stage-counter", "job-name", 3L, "file-path", 3, multipartHttpServletRequest);
    ResponseCodeView codeView = (ResponseCodeView) modelAndView.getView();

    assertThat(codeView.getStatusCode(), is(HttpServletResponse.SC_BAD_REQUEST));
    assertThat(codeView.getContent(), is("Missing required header 'Confirm'"));

}
 
Example 17
Source Project: jeewx-boot   Source File: MyJwWebJwid3Controller.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 保存图片
 * @return
 */
@RequestMapping(value = "/doUpload",method ={RequestMethod.POST})
@ResponseBody
public AjaxJson doUpload(MultipartHttpServletRequest request,HttpServletResponse response){
	AjaxJson j = new AjaxJson();
	try {
		MultipartFile uploadify = request.getFile("file");
        byte[] bytes = uploadify.getBytes();  
        String realFilename=uploadify.getOriginalFilename();
        String fileExtension = realFilename.substring(realFilename.lastIndexOf("."));
        String filename=UUID.randomUUID().toString().replace("-", "")+fileExtension;
        String uploadDir = request.getSession().getServletContext().getRealPath("upload/img/commonweixin/");   
        File dirPath = new File(uploadDir);  
        if (!dirPath.exists()) {  
            dirPath.mkdirs();  
        }  
        String sep = System.getProperty("file.separator");  
        File uploadedFile = new File(uploadDir + sep  + filename);  
        FileCopyUtils.copy(bytes, uploadedFile);  
        j.setObj(filename);
        j.setSuccess(true);
		j.setMsg("保存成功");
	} catch (Exception e) {
		e.printStackTrace();
		j.setSuccess(false);
		j.setMsg("保存失败");
	}
	return j;
}
 
Example 18
Source Project: jeewx-boot   Source File: CmsAdController.java    License: Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "doUploadFile",method ={RequestMethod.POST,RequestMethod.GET})
@ResponseBody
public AjaxJson doUploadFile(MultipartHttpServletRequest request,HttpServletResponse response){
	AjaxJson j = new AjaxJson();
	try {
		MultipartFile uploadify = request.getFile("file");
		// -----update--begin--author:zhaofei-----date:20191024---for:小程序上传云-----------------
        /*byte[] bytes = uploadify.getBytes();
        //String uploadDir = request.getSession().getServletContext().getRealPath(CmsCommonUtil.FILE_BIZ_PATH);
		String uploadDir = upLoadPath + "/upload/img/cms";
        String sep = System.getProperty("file.separator");
        File dirPath = new File(uploadDir);
        if (!dirPath.exists()) {
            dirPath.mkdirs();
        }
        String realFilename=uploadify.getOriginalFilename();
        String filename = CmsCommonUtil.getUploadFileName(realFilename);
        File uploadedFile = new File(uploadDir + sep + filename);
        FileCopyUtils.copy(bytes, uploadedFile);*/
		String filename = OSSBootUtil.upload(uploadify,"upload/img/cms");
		// -----update--end--author:zhaofei-----date:20191024---for:小程序上传云-----------------
		j.setObj(filename);
		j.setMsg("保存成功");
	} catch (Exception e) {
		j.setSuccess(false);
		j.setMsg("操作失败"+e.getMessage());
	}
	return j;
}
 
Example 19
private void doTestWithApplicationContext(boolean lazy) throws Exception {
	StaticWebApplicationContext wac = new StaticWebApplicationContext();
	wac.setServletContext(new MockServletContext());
	wac.getServletContext().setAttribute(WebUtils.TEMP_DIR_CONTEXT_ATTRIBUTE, new File("mytemp"));
	wac.refresh();
	MockCommonsMultipartResolver resolver = new MockCommonsMultipartResolver();
	resolver.setMaxUploadSize(1000);
	resolver.setMaxInMemorySize(100);
	resolver.setDefaultEncoding("enc");
	if (lazy) {
		resolver.setResolveLazily(false);
	}
	resolver.setServletContext(wac.getServletContext());
	assertEquals(1000, resolver.getFileUpload().getSizeMax());
	assertEquals(100, resolver.getFileItemFactory().getSizeThreshold());
	assertEquals("enc", resolver.getFileUpload().getHeaderEncoding());
	assertTrue(resolver.getFileItemFactory().getRepository().getAbsolutePath().endsWith("mytemp"));

	MockHttpServletRequest originalRequest = new MockHttpServletRequest();
	originalRequest.setMethod("POST");
	originalRequest.setContentType("multipart/form-data");
	originalRequest.addHeader("Content-type", "multipart/form-data");
	originalRequest.addParameter("getField", "getValue");
	assertTrue(resolver.isMultipart(originalRequest));
	MultipartHttpServletRequest request = resolver.resolveMultipart(originalRequest);

	doTestParameters(request);

	doTestFiles(request);

	doTestBinding(resolver, originalRequest, request);

	wac.close();
}
 
Example 20
Source Project: CheckPoint   Source File: MsgSettingServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void updateValidationData(MultipartHttpServletRequest req) {
    req.getMultiFileMap().entrySet().forEach(entry -> {
        List<MultipartFile> files = entry.getValue();
        this.updateFromFiles(files);
    });

    this.validationDataRepository.flush();
    this.validationStore.refresh();
}
 
Example 21
@Override
public void cleanupMultipart(MultipartHttpServletRequest request) {
	if (request != null) {
		try {
			cleanupFileItems(request.getMultiFileMap());
		}
		catch (Throwable ex) {
			logger.warn("Failed to perform multipart cleanup for servlet request", ex);
		}
	}
}
 
Example 22
@Test
public void withServletContextAndFilter() throws Exception {
	StaticWebApplicationContext wac = new StaticWebApplicationContext();
	wac.setServletContext(new MockServletContext());
	wac.registerSingleton("filterMultipartResolver", MockCommonsMultipartResolver.class, new MutablePropertyValues());
	wac.getServletContext().setAttribute(WebUtils.TEMP_DIR_CONTEXT_ATTRIBUTE, new File("mytemp"));
	wac.refresh();
	wac.getServletContext().setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
	CommonsMultipartResolver resolver = new CommonsMultipartResolver(wac.getServletContext());
	assertTrue(resolver.getFileItemFactory().getRepository().getAbsolutePath().endsWith("mytemp"));

	MockFilterConfig filterConfig = new MockFilterConfig(wac.getServletContext(), "filter");
	filterConfig.addInitParameter("class", "notWritable");
	filterConfig.addInitParameter("unknownParam", "someValue");
	final MultipartFilter filter = new MultipartFilter();
	filter.init(filterConfig);

	final List<MultipartFile> files = new ArrayList<MultipartFile>();
	final FilterChain filterChain = new FilterChain() {
		@Override
		public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) {
			MultipartHttpServletRequest request = (MultipartHttpServletRequest) servletRequest;
			files.addAll(request.getFileMap().values());
		}
	};

	FilterChain filterChain2 = new PassThroughFilterChain(filter, filterChain);

	MockHttpServletRequest originalRequest = new MockHttpServletRequest();
	MockHttpServletResponse response = new MockHttpServletResponse();
	originalRequest.setMethod("POST");
	originalRequest.setContentType("multipart/form-data");
	originalRequest.addHeader("Content-type", "multipart/form-data");
	filter.doFilter(originalRequest, response, filterChain2);

	CommonsMultipartFile file1 = (CommonsMultipartFile) files.get(0);
	CommonsMultipartFile file2 = (CommonsMultipartFile) files.get(1);
	assertTrue(((MockFileItem) file1.getFileItem()).deleted);
	assertTrue(((MockFileItem) file2.getFileItem()).deleted);
}
 
Example 23
Source Project: spring-analysis-note   Source File: DispatcherServlet.java    License: MIT License 5 votes vote down vote up
/**
 * Clean up any resources used by the given multipart request (if any).
 * @param request current HTTP request
 * @see MultipartResolver#cleanupMultipart
 */
protected void cleanupMultipart(HttpServletRequest request) {
	if (this.multipartResolver != null) {
		MultipartHttpServletRequest multipartRequest =
				WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class);
		if (multipartRequest != null) {
			this.multipartResolver.cleanupMultipart(multipartRequest);
		}
	}
}
 
Example 24
@Override
public void doSomething(HttpServletRequest request) throws ServletException, IllegalAccessException {
	WebApplicationContext wac = RequestContextUtils.findWebApplicationContext(request);
	if (!(wac instanceof ComplexWebApplicationContext)) {
		throw new ServletException("Incorrect WebApplicationContext");
	}
	if (WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class) == null) {
		throw new ServletException("Not in a MultipartHttpServletRequest");
	}
	if (request.getParameter("fail") != null) {
		throw new ModelAndViewDefiningException(new ModelAndView("failed1"));
	}
	if (request.getParameter("access") != null) {
		throw new IllegalAccessException("illegal access");
	}
	if (request.getParameter("servlet") != null) {
		throw new ServletRequestBindingException("servlet");
	}
	if (request.getParameter("exception") != null) {
		throw new RuntimeException("servlet");
	}
	if (!(RequestContextUtils.getLocaleResolver(request) instanceof SessionLocaleResolver)) {
		throw new ServletException("Incorrect LocaleResolver");
	}
	if (!Locale.CANADA.equals(RequestContextUtils.getLocale(request))) {
		throw new ServletException("Incorrect Locale");
	}
	if (!Locale.CANADA.equals(LocaleContextHolder.getLocale())) {
		throw new ServletException("Incorrect Locale");
	}
	if (RequestContextUtils.getTimeZone(request) != null) {
		throw new ServletException("Incorrect TimeZone");
	}
	if (!TimeZone.getDefault().equals(LocaleContextHolder.getTimeZone())) {
		throw new ServletException("Incorrect TimeZone");
	}
	if (!(RequestContextUtils.getThemeResolver(request) instanceof SessionThemeResolver)) {
		throw new ServletException("Incorrect ThemeResolver");
	}
	if (!"theme".equals(RequestContextUtils.getThemeResolver(request).resolveThemeName(request))) {
		throw new ServletException("Incorrect theme name");
	}
	RequestContext rc = new RequestContext(request);
	rc.changeLocale(Locale.US, TimeZone.getTimeZone("GMT+1"));
	rc.changeTheme("theme2");
	if (!Locale.US.equals(RequestContextUtils.getLocale(request))) {
		throw new ServletException("Incorrect Locale");
	}
	if (!Locale.US.equals(LocaleContextHolder.getLocale())) {
		throw new ServletException("Incorrect Locale");
	}
	if (!TimeZone.getTimeZone("GMT+1").equals(RequestContextUtils.getTimeZone(request))) {
		throw new ServletException("Incorrect TimeZone");
	}
	if (!TimeZone.getTimeZone("GMT+1").equals(LocaleContextHolder.getTimeZone())) {
		throw new ServletException("Incorrect TimeZone");
	}
	if (!"theme2".equals(RequestContextUtils.getThemeResolver(request).resolveThemeName(request))) {
		throw new ServletException("Incorrect theme name");
	}
}
 
Example 25
@Override
public void cleanupMultipart(MultipartHttpServletRequest request) {
	if (request.getAttribute("cleanedUp") != null) {
		throw new IllegalStateException("Already cleaned up");
	}
	request.setAttribute("cleanedUp", Boolean.TRUE);
}
 
Example 26
private void doTestMultipartHttpServletRequest(MultipartHttpServletRequest request) throws IOException {
	Set<String> fileNames = new HashSet<String>();
	Iterator<String> fileIter = request.getFileNames();
	while (fileIter.hasNext()) {
		fileNames.add(fileIter.next());
	}
	assertEquals(2, fileNames.size());
	assertTrue(fileNames.contains("file1"));
	assertTrue(fileNames.contains("file2"));
	MultipartFile file1 = request.getFile("file1");
	MultipartFile file2 = request.getFile("file2");
	Map<String, MultipartFile> fileMap = request.getFileMap();
	List<String> fileMapKeys = new LinkedList<String>(fileMap.keySet());
	assertEquals(2, fileMapKeys.size());
	assertEquals(file1, fileMap.get("file1"));
	assertEquals(file2, fileMap.get("file2"));

	assertEquals("file1", file1.getName());
	assertEquals("", file1.getOriginalFilename());
	assertNull(file1.getContentType());
	assertTrue(ObjectUtils.nullSafeEquals("myContent1".getBytes(), file1.getBytes()));
	assertTrue(ObjectUtils.nullSafeEquals("myContent1".getBytes(),
		FileCopyUtils.copyToByteArray(file1.getInputStream())));
	assertEquals("file2", file2.getName());
	assertEquals("myOrigFilename", file2.getOriginalFilename());
	assertEquals("text/plain", file2.getContentType());
	assertTrue(ObjectUtils.nullSafeEquals("myContent2".getBytes(), file2.getBytes()));
	assertTrue(ObjectUtils.nullSafeEquals("myContent2".getBytes(),
		FileCopyUtils.copyToByteArray(file2.getInputStream())));
}
 
Example 27
Source Project: spring-analysis-note   Source File: MultipartResolutionDelegate.java    License: MIT License 5 votes vote down vote up
static MultipartHttpServletRequest asMultipartHttpServletRequest(HttpServletRequest request) {
	MultipartHttpServletRequest unwrapped = WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class);
	if (unwrapped != null) {
		return unwrapped;
	}
	return new StandardMultipartHttpServletRequest(request);
}
 
Example 28
Source Project: jeewx   Source File: AlipayGzuserinfoController.java    License: Apache License 2.0 5 votes vote down vote up
/**
	 * 保存信息
	 * @return
	 */
	@RequestMapping(params = "doAdd",method ={RequestMethod.GET, RequestMethod.POST})
	@ResponseBody
	public AjaxJson doAdd(HttpServletRequest request , @ModelAttribute AlipayGzuserinfo alipayGzuserinfo){
		AjaxJson j = new AjaxJson();
		try {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		    MultipartFile uploadfile = multipartRequest.getFile("avatar_file");
			//对数据进行校验
			//1.1身份认证信息(微信号/手机/邮箱)不能同时为空
			if(StringUtils.isBlank(alipayGzuserinfo.getWeixinid()) && StringUtils.isBlank(alipayGzuserinfo.getMobile()) && StringUtils.isBlank(alipayGzuserinfo.getEmail())){
				throw new Exception("微信号/手机/邮箱 不能同时为空");
			}
		    String randomSeed = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
		    alipayGzuserinfo.setId(randomSeed);
		    alipayGzuserinfo.setCreateDate(new Date());
		    
		  
		    
		    alipayGzuserinfoService.saveGzuserinfo(alipayGzuserinfo,uploadfile, request);
//			alipayGzuserinfoDao.insert(alipayGzuserinfo);
			//还需要对微信接口进行调整
			j.setMsg("保存成功");
		} catch (Exception e) {
		    log.info(e.getMessage());
			j.setSuccess(false);
			j.setMsg("保存失败,详细原因:"+e.getMessage());
		}
		return j;
	}
 
Example 29
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 30
@Test
public void withServletContextAndFilter() throws Exception {
	StaticWebApplicationContext wac = new StaticWebApplicationContext();
	wac.setServletContext(new MockServletContext());
	wac.registerSingleton("filterMultipartResolver", MockCommonsMultipartResolver.class, new MutablePropertyValues());
	wac.getServletContext().setAttribute(WebUtils.TEMP_DIR_CONTEXT_ATTRIBUTE, new File("mytemp"));
	wac.refresh();
	wac.getServletContext().setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
	CommonsMultipartResolver resolver = new CommonsMultipartResolver(wac.getServletContext());
	assertTrue(resolver.getFileItemFactory().getRepository().getAbsolutePath().endsWith("mytemp"));

	MockFilterConfig filterConfig = new MockFilterConfig(wac.getServletContext(), "filter");
	filterConfig.addInitParameter("class", "notWritable");
	filterConfig.addInitParameter("unknownParam", "someValue");
	final MultipartFilter filter = new MultipartFilter();
	filter.init(filterConfig);

	final List<MultipartFile> files = new ArrayList<>();
	final FilterChain filterChain = new FilterChain() {
		@Override
		public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) {
			MultipartHttpServletRequest request = (MultipartHttpServletRequest) servletRequest;
			files.addAll(request.getFileMap().values());
		}
	};

	FilterChain filterChain2 = new PassThroughFilterChain(filter, filterChain);

	MockHttpServletRequest originalRequest = new MockHttpServletRequest();
	MockHttpServletResponse response = new MockHttpServletResponse();
	originalRequest.setMethod("POST");
	originalRequest.setContentType("multipart/form-data");
	originalRequest.addHeader("Content-type", "multipart/form-data");
	filter.doFilter(originalRequest, response, filterChain2);

	CommonsMultipartFile file1 = (CommonsMultipartFile) files.get(0);
	CommonsMultipartFile file2 = (CommonsMultipartFile) files.get(1);
	assertTrue(((MockFileItem) file1.getFileItem()).deleted);
	assertTrue(((MockFileItem) file2.getFileItem()).deleted);
}