org.springframework.web.multipart.MultipartHttpServletRequest Java Examples

The following examples show how to use org.springframework.web.multipart.MultipartHttpServletRequest. 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: Adm2000Controller.java    From oslits with 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 #2
Source File: FeedbackAttachmentServiceImpl.java    From agile-service-old with Apache License 2.0 6 votes vote down vote up
@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 #3
Source File: StandardServletMultipartResolver.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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
Source File: RequestPartServletServerHttpRequest.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #5
Source File: SysUploadController.java    From jeecg-cloud with 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 #6
Source File: FileUploadController.java    From charging_pile_cloud with 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 #7
Source File: IssueAttachmentServiceImpl.java    From agile-service-old with Apache License 2.0 6 votes vote down vote up
@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 #8
Source File: JeecgBlobDataController.java    From jeewx with 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 #9
Source File: UploadInterceptor.java    From hdw-dubbo with 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 #10
Source File: GrailsDataBinder.java    From AlgoTrader with 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 #11
Source File: AttachmentFile.java    From wangmarket with 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 File: QywxGzuserinfoController.java    From jeewx with 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 File: AttachmentFile.java    From wangmarket with 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 #14
Source File: SysUploadController.java    From teaching with 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 #15
Source File: AlipayGzuserinfoController.java    From jeewx with 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 #16
Source File: CommonsMultipartResolverTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
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 #17
Source File: CommonsMultipartResolverTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
protected FileUpload newFileUpload(FileItemFactory fileItemFactory) {
	return new ServletFileUpload() {
		@Override
		public List<FileItem> parseRequest(HttpServletRequest request) {
			if (request instanceof MultipartHttpServletRequest) {
				throw new IllegalStateException("Already a multipart request");
			}
			List<FileItem> fileItems = new ArrayList<>();
			MockFileItem fileItem1 = new MockFileItem(
				"field1", "type1", empty ? "" : "field1.txt", empty ? "" : "text1");
			MockFileItem fileItem1x = new MockFileItem(
				"field1", "type1", empty ? "" : "field1.txt", empty ? "" : "text1");
			MockFileItem fileItem2 = new MockFileItem(
				"field2", "type2", empty ? "" : "C:\\mypath/field2.txt", empty ? "" : "text2");
			MockFileItem fileItem2x = new MockFileItem(
				"field2x", "type2", empty ? "" : "C:/mypath\\field2x.txt", empty ? "" : "text2");
			MockFileItem fileItem3 = new MockFileItem("field3", null, null, "value3");
			MockFileItem fileItem4 = new MockFileItem("field4", "text/html; charset=iso-8859-1", null, "value4");
			MockFileItem fileItem5 = new MockFileItem("field4", null, null, "value5");
			fileItems.add(fileItem1);
			fileItems.add(fileItem1x);
			fileItems.add(fileItem2);
			fileItems.add(fileItem2x);
			fileItems.add(fileItem3);
			fileItems.add(fileItem4);
			fileItems.add(fileItem5);
			return fileItems;
		}
	};
}
 
Example #18
Source File: MockMultipartHttpServletRequestTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private void doTestMultipartHttpServletRequest(MultipartHttpServletRequest request) throws IOException {
	Set<String> fileNames = new HashSet<>();
	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<>(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 #19
Source File: JwSystemProjectController.java    From jeewx-boot with 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 #20
Source File: FileMangerController.java    From efo with MIT License 5 votes vote down vote up
/**
 * 暂时没有找到更好的解决方案
 *
 * @param destination 目的
 *
 * @return 响应结果
 */
@AuthInterceptor(InterceptorLevel.SYSTEM)
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String upload(String destination, MultipartHttpServletRequest request) {
    Map<String, MultipartFile> fileMap = request.getFileMap();
    MultipartFile[] files = ArrayUtils.mapToArray(fileMap, MultipartFile.class);
    jsonObject.put("result", fileManagerService.upload(destination, files));
    return jsonObject.toJSONString();
}
 
Example #21
Source File: DocUploadController.java    From mumu with Apache License 2.0 5 votes vote down vote up
/**
 * 上传文件
 * @param request
 * @return
 */
public File uploadFile(HttpServletRequest request) {
    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
    try {
        if (multipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            Iterator<String> iterator = multiRequest.getFileNames();
            while (iterator.hasNext()) {
                String key = iterator.next();
                MultipartFile multipartFile = multiRequest.getFile(key);
                if (multipartFile != null) {
                    String name = multipartFile.getOriginalFilename();
                    String pathDir = request.getSession().getServletContext().getRealPath("/upload/" + DateUtils.currentTime());
                    File dirFile = new File(pathDir);
                    if (!dirFile.isDirectory()) {
                        dirFile.mkdirs();
                    }
                    String filePath = pathDir+File.separator+name;
                    File file = new File(filePath);
                    file.setWritable(true, false);

                    multipartFile.transferTo(file);
                    return file;
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example #22
Source File: UploadController.java    From uexam-mysql with GNU Affero General Public License v3.0 5 votes vote down vote up
@RequestMapping("/image")
@ResponseBody
public RestResponse questionUploadAndReadExcel(HttpServletRequest request) {
    MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
    MultipartFile multipartFile = multipartHttpServletRequest.getFile("file");
    long attachSize = multipartFile.getSize();
    String imgName = multipartFile.getOriginalFilename();
    try (InputStream inputStream = multipartFile.getInputStream()) {
        String filePath = fileUpload.uploadFile(inputStream, attachSize, imgName);
        userService.changePicture(getCurrentUser(), filePath);
        return RestResponse.ok(filePath);
    } catch (IOException e) {
        return RestResponse.fail(2, e.getMessage());
    }
}
 
Example #23
Source File: UploadController.java    From uexam-mysql with GNU Affero General Public License v3.0 5 votes vote down vote up
@RequestMapping("/image")
@ResponseBody
public RestResponse questionUploadAndReadExcel(HttpServletRequest request) {
    MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
    MultipartFile multipartFile = multipartHttpServletRequest.getFile("file");
    long attachSize = multipartFile.getSize();
    String imgName = multipartFile.getOriginalFilename();
    try (InputStream inputStream = multipartFile.getInputStream()) {
        String filePath = fileUpload.uploadFile(inputStream, attachSize, imgName);
        userService.changePicture(getCurrentUser(), filePath);
        return RestResponse.ok(filePath);
    } catch (IOException e) {
        return RestResponse.fail(2, e.getMessage());
    }
}
 
Example #24
Source File: ProductManagerController.java    From Project with Apache License 2.0 5 votes vote down vote up
/**
 * 处理图片
 *
 * @param request
 * @param productImgList
 * @return
 * @throws IOException
 */
private ImageHolder handleImage(HttpServletRequest request, List<ImageHolder> productImgList) throws IOException {
    MultipartHttpServletRequest multipartHttpServletRequest =
            (MultipartHttpServletRequest) request;
    ImageHolder thumbnail = null;

    // 取出缩略图并构建 ImageHolder 对象
    CommonsMultipartFile thumbnailFile =
            (CommonsMultipartFile) multipartHttpServletRequest.getFile("thumbnail");
    thumbnail = new ImageHolder(thumbnailFile.getInputStream(),
            thumbnailFile.getOriginalFilename());
    // 取出详情图列表并构建List<ImageHolder>列表对象,最多支持6张图片上传
    for (int i = 0; i < IMAGE_MAX_UPDATE_COUNT; i++) {
        CommonsMultipartFile productImgFile =
                (CommonsMultipartFile) multipartHttpServletRequest.getFile("productImg" + i);
        if (productImgFile != null) {
            // 若取出的详情图片文件流不为空,则将其加入详情图列表
            ImageHolder productImg = new ImageHolder(productImgFile.getInputStream(),
                    productImgFile.getOriginalFilename());
            productImgList.add(productImg);
        } else {
            // 若取出的详情图片文件流为空,则终止循环
            break;
        }
    }
    return thumbnail;
}
 
Example #25
Source File: DispatcherServlet.java    From java-technology-stack with 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 File: WxMaMediaController.java    From sdb-mall with Apache License 2.0 5 votes vote down vote up
/**
 * 上传临时素材
 *
 * @return 素材的media_id列表,实际上如果有的话,只会有一个
 */
@PostMapping("/upload")
public List<String> uploadMedia(HttpServletRequest request) throws WxErrorException {
    CommonsMultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());

    if (!resolver.isMultipart(request)) {
        return Lists.newArrayList();
    }

    MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
    Iterator<String> it = multiRequest.getFileNames();
    List<String> result = Lists.newArrayList();
    while (it.hasNext()) {
        try {
            MultipartFile file = multiRequest.getFile(it.next());
            File newFile = new File(Files.createTempDir(), file.getOriginalFilename());
            this.logger.info("filePath is :" + newFile.toString());
            file.transferTo(newFile);
            WxMediaUploadResult uploadResult = this.service.getMediaService().uploadMedia(WxMaConstants.KefuMsgType.IMAGE, newFile);
            this.logger.info("media_id : " + uploadResult.getMediaId());
            result.add(uploadResult.getMediaId());
        } catch (IOException e) {
            this.logger.error(e.getMessage(), e);
        }
    }

    return result;
}
 
Example #27
Source File: ImageController.java    From BlogSystem with Apache License 2.0 5 votes vote down vote up
/**
 * 上传图片
 */
@RequestMapping(method = RequestMethod.POST)
@ResponseBody
public ResultBean upload(MultipartHttpServletRequest request,
                         @PathVariable("bloggerId") Integer bloggerId,
                         @RequestParam(value = "category", required = false) Integer category,
                         @RequestParam(value = "bewrite", required = false) String bewrite,
                         @RequestParam(value = "title", required = false) String title) {
    handleBloggerSignInCheck(request, bloggerId);

    MultipartFile file = request.getFile("image");// 与页面input的name相同
    int id;
    if (ImageUtils.isImageFile(file)) {

        // 默认上传到私有目录
        int cate = category == null ? BloggerPictureCategoryEnum.PRIVATE.getCode() : category;

        // 普通用户没有指定图片类别的必要
        //检查博主权限
        if (!validateManager.checkBloggerPictureLegal(bloggerId, cate)) {
            throw exceptionManager.getUnauthorizedException(new RequestContext(request));
        }

        id = bloggerPictureService.insertPicture(file, bloggerId, bewrite, BloggerPictureCategoryEnum.valueOf(cate),
                title);
        if (id <= 0) handlerOperateFail(request);
    } else {
        return new ResultBean(exceptionManager.getPictureFormatErrorException(new RequestContext(request)));
    }

    return new ResultBean<>(id);
}
 
Example #28
Source File: CommonsMultipartResolver.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public void cleanupMultipart(MultipartHttpServletRequest request) {
	if (!(request instanceof AbstractMultipartHttpServletRequest) ||
			((AbstractMultipartHttpServletRequest) request).isResolved()) {
		try {
			cleanupFileItems(request.getMultiFileMap());
		}
		catch (Throwable ex) {
			logger.warn("Failed to perform multipart cleanup for servlet request", ex);
		}
	}
}
 
Example #29
Source File: FileTools.java    From jcalaBlog with MIT License 5 votes vote down vote up
/**
 * 从HttpServletRequest中获取MultipartFile
 */
private static MultipartFile getMultipartFile(HttpServletRequest request) {
    MultipartHttpServletRequest multipartRequest =
            (MultipartHttpServletRequest) request;
    Iterator<String> fileNames = multipartRequest.getFileNames();
    return multipartRequest.getFile(fileNames.next());
}
 
Example #30
Source File: ExecutionVariableResource.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
@ApiOperation(value = "Update a variable on an execution", tags = {"Executions"}, nickname = "updateExecutionVariable")
@ApiResponses(value = {
    @ApiResponse(code = 200, message = "Indicates both the process instance and variable were found and variable is updated."),
    @ApiResponse(code = 404, message = "Indicates the requested process instance was not found or the process instance does not have a variable with the given name. Status description contains additional information about the error.")
})
@RequestMapping(value = "/runtime/executions/{executionId}/variables/{variableName}", method = RequestMethod.PUT, produces = "application/json")
public RestVariable updateVariable(@ApiParam(name = "executionId", value="The id of the execution to create the new variable for.") @PathVariable("executionId") String executionId,@ApiParam(name = "variableName", value="The name of the variable to update.") @PathVariable("variableName") String variableName, HttpServletRequest request) {

  Execution execution = getExecutionFromRequest(executionId);

  RestVariable result = null;
  if (request instanceof MultipartHttpServletRequest) {
    result = setBinaryVariable((MultipartHttpServletRequest) request, execution, RestResponseFactory.VARIABLE_EXECUTION, false);

    if (!result.getName().equals(variableName)) {
      throw new ActivitiIllegalArgumentException("Variable name in the body should be equal to the name used in the requested URL.");
    }

  } else {

    RestVariable restVariable = null;

    try {
      restVariable = objectMapper.readValue(request.getInputStream(), RestVariable.class);
    } catch (Exception e) {
      throw new ActivitiIllegalArgumentException("Error converting request body to RestVariable instance", e);
    }

    if (restVariable == null) {
      throw new ActivitiException("Invalid body was supplied");
    }
    if (!restVariable.getName().equals(variableName)) {
      throw new ActivitiIllegalArgumentException("Variable name in the body should be equal to the name used in the requested URL.");
    }

    result = setSimpleVariable(restVariable, execution, false);
  }
  return result;
}