Java Code Examples for org.springframework.web.multipart.MultipartHttpServletRequest#getFileMap()
The following examples show how to use
org.springframework.web.multipart.MultipartHttpServletRequest#getFileMap() .
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: FileOperateUtil.java From kkFileViewOfficeEdit with Apache License 2.0 | 6 votes |
/** * 上传 * * @param request * @throws IOException */ public static void upload(HttpServletRequest request) throws IOException { MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request; Map<String, MultipartFile> fileMap = mRequest.getFileMap(); File file = new File(FILEDIR); if (!file.exists()) { file.mkdir(); } Iterator<Map.Entry<String, MultipartFile>> it = fileMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, MultipartFile> entry = it.next(); MultipartFile mFile = entry.getValue(); if (mFile.getSize() != 0 && !"".equals(mFile.getName())) { write(mFile.getInputStream(), new FileOutputStream(initFilePath(mFile.getOriginalFilename()))); } } }
Example 2
Source File: JeecgBlobDataController.java From jeewx with Apache License 2.0 | 6 votes |
@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 3
Source File: WebOfficeController.java From jeewx with Apache License 2.0 | 6 votes |
@RequestMapping(params = "saveDoc") @ResponseBody public AjaxJson saveDoc(WebOfficeEntity webOffice, HttpServletRequest request, 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 { webOfficeService.saveObj(webOffice, file); j.setMsg("文件导入成功!"); } catch (Exception e) { j.setMsg("文件导入失败!"); logger.error(ExceptionUtil.getExceptionMessage(e)); } //break; // 不支持多个文件导入? } return j; }
Example 4
Source File: Adm2000Controller.java From oslits with GNU General Public License v3.0 | 6 votes |
/** * 사용자 정보가 기록된 엑셀파일 업로드 처리 * 엑셀의 사용자 정보 리스트 전달 * @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 5
Source File: MockMultipartHttpServletRequestTests.java From spring-analysis-note with MIT License | 5 votes |
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 6
Source File: JpPersonController.java From jeewx with Apache License 2.0 | 5 votes |
@RequestMapping(params = "importExcel", method = RequestMethod.POST) @ResponseBody public AjaxJson importExcel(HttpServletRequest request, 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();// 获取上传文件对象 List<JpPersonEntity> listPersons; try { listPersons = (List<JpPersonEntity>) ExcelUtil.importExcelByIs(file.getInputStream(), JpPersonEntity.class); for (JpPersonEntity person : listPersons) { if(person.getAge()!=null){ person.setId(UUIDGenerator.generate()); jpPersonService.save(person); } } j.setMsg("文件导入成功!"); } catch (IOException e) { j.setMsg("文件导入失败!"); logger.error(ExceptionUtil.getExceptionMessage(e)); } //break; // 不支持多个文件导入? } return j; }
Example 7
Source File: MockMultipartHttpServletRequestTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
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 8
Source File: FileUploadController.java From springboot-learn with MIT License | 5 votes |
@PostMapping(value = "/upload") public Result upload(HttpServletRequest request) { Result result = new Result(ResultCode.SUCCESS); if (request instanceof MultipartHttpServletRequest) { MultipartHttpServletRequest mhr = (MultipartHttpServletRequest) request; Map<String, MultipartFile> mmf = mhr.getFileMap(); result = FileUploadUtil.upload(mmf, "file", ""); } else { result.setStatus(ResultCode.ERROR.getStatus()); result.setInfo("该请求不是multipart/form-data类型请求!"); } return result; }
Example 9
Source File: UploadController.java From tianti with Apache License 2.0 | 5 votes |
@RequestMapping("/uploadAttach") public void uploadAttach(HttpServletRequest request, PrintWriter out) { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; Map<String, MultipartFile> fileMap = multipartRequest.getFileMap(); MultipartFile multipartFile = null; String fileName = null; for (Map.Entry<String, MultipartFile> set : fileMap.entrySet()) { multipartFile = set.getValue();// 文件名 } fileName = this.storeIOc(multipartRequest, multipartFile); out.print(fileName); }
Example 10
Source File: CommonController.java From jeewx with Apache License 2.0 | 5 votes |
/** * 生成XML文件parserXml * * @return */ @RequestMapping(params = "parserXml") @ResponseBody public AjaxJson parserXml(HttpServletRequest request, HttpServletResponse response) { AjaxJson json = new AjaxJson(); String fileName = null; UploadFile uploadFile = new UploadFile(request); String ctxPath = request.getSession().getServletContext().getRealPath(""); File file = new File(ctxPath); if (!file.exists()) { file.mkdir();// 创建文件根目录 } MultipartHttpServletRequest multipartRequest = uploadFile.getMultipartRequest(); Map<String, MultipartFile> fileMap = multipartRequest.getFileMap(); for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) { MultipartFile mf = entity.getValue();// 获取上传文件对象 fileName = mf.getOriginalFilename();// 获取文件名 String savePath = file.getPath() + "/" + fileName; File savefile = new File(savePath); try { FileCopyUtils.copy(mf.getBytes(), savefile); } catch (IOException e) { e.printStackTrace(); } } systemService.parserXml(ctxPath + "/" + fileName); json.setSuccess(true); return json; }
Example 11
Source File: CommonController.java From jeecg with Apache License 2.0 | 5 votes |
/** * 生成XML文件parserXml * * @return */ @RequestMapping(params = "parserXml") @ResponseBody public AjaxJson parserXml(HttpServletRequest request, HttpServletResponse response) { AjaxJson json = new AjaxJson(); String fileName = null; UploadFile uploadFile = new UploadFile(request); String ctxPath = request.getSession().getServletContext().getRealPath(""); File file = new File(ctxPath); if (!file.exists()) { file.mkdir();// 创建文件根目录 } MultipartHttpServletRequest multipartRequest = uploadFile.getMultipartRequest(); Map<String, MultipartFile> fileMap = multipartRequest.getFileMap(); for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) { MultipartFile mf = entity.getValue();// 获取上传文件对象 fileName = mf.getOriginalFilename();// 获取文件名 String savePath = file.getPath() + "/" + fileName; File savefile = new File(savePath); try { FileCopyUtils.copy(mf.getBytes(), savefile); } catch (IOException e) { e.printStackTrace(); } } systemService.parserXml(ctxPath + "/" + fileName); json.setSuccess(true); return json; }
Example 12
Source File: FileMangerController.java From efo with MIT License | 5 votes |
/** * 暂时没有找到更好的解决方案 * * @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 13
Source File: MockMultipartHttpServletRequestTests.java From java-technology-stack with MIT License | 5 votes |
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 14
Source File: CgformSqlController.java From jeewx with Apache License 2.0 | 4 votes |
/** * 导入Form(采用SQL方式) * * @param ids * @return * @throws Exception */ @RequestMapping(params = "doMigrateIn", method = RequestMethod.POST) @ResponseBody public AjaxJson doMigrateIn(HttpServletRequest request, HttpServletResponse response) { AjaxJson j = new AjaxJson(); String ls_file = ""; UploadFile uploadFile = new UploadFile(request, ls_file); uploadFile.setCusPath(""); uploadFile.setSwfpath(""); String uploadbasepath = uploadFile.getBasePath();// 文件上传根目录 if (uploadbasepath == null) { uploadbasepath = ResourceUtil.getConfigByName("uploadpath"); } String path = uploadbasepath + "\\";// 文件保存在硬盘的相对路径 String realPath = uploadFile.getMultipartRequest().getSession() .getServletContext().getRealPath("\\") + path;// 文件的硬盘真实路径 message = null; try { File file = new File(realPath); if (!file.exists()) { file.mkdir();// 若目录不存在,创建根目录 } uploadFile.getMultipartRequest().setCharacterEncoding("UTF-8"); MultipartHttpServletRequest multipartRequest = uploadFile .getMultipartRequest(); Map<String, MultipartFile> fileMap = multipartRequest.getFileMap(); String fileName = ""; for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) { MultipartFile mf = entity.getValue();// 获取上传文件对象 fileName = mf.getOriginalFilename();// 获取文件名 String savePath = realPath + fileName; File savefile = new File(savePath); String ls_tmp = savefile.getName(); /*String sqlfilename = realPath + ls_tmp.substring(0, ls_tmp.lastIndexOf(".")) + "\\" + ls_tmp.substring(0, ls_tmp.lastIndexOf(".")) + ".sql";*/ FileCopyUtils.copy(mf.getBytes(), savefile); MigrateForm.unzip(savePath, ""); String sqlFileDir = realPath + ls_tmp.substring(0, ls_tmp.lastIndexOf(".")); File sqlDirFile = new File(sqlFileDir); String sqlfilename = sqlDirFile.getPath() + "/"; if(sqlDirFile.isDirectory()){ sqlfilename += sqlDirFile.list()[0]; } /*OfficeHtmlUtil officeHtml = new OfficeHtmlUtil(); String sqlStr = officeHtml.getInfo(sqlfilename); String[] sqlStrs = sqlStr.split(";"); for (String exesql : sqlStrs) { if (!StringUtil.isEmpty(exesql) && !"\n".equals(exesql)) { jdbcTemplate.execute(exesql); } }*/ XStream xStream = new XStream(); xStream.processAnnotations(DBTable.class); @SuppressWarnings("unchecked") List<DBTable> dbTables = (List<DBTable>) xStream.fromXML(new File(sqlfilename)); if(!dbTables.isEmpty() && dbTables.size()>0){ for (DBTable dbTable : dbTables) { mergeMigrateInComponent(dbTable); } } } } catch (Exception e1) { e1.printStackTrace(); LogUtil.error(e1.toString()); message = e1.toString(); } if (StringUtil.isNotEmpty(message)) j.setMsg("SQL文件导入失败," + message); else j.setMsg("SQL文件导入成功"); return j; }
Example 15
Source File: CgformSqlController.java From jeecg with Apache License 2.0 | 4 votes |
/** * 导入Form(采用XML方式) * * @param ids * @return * @throws Exception */ @RequestMapping(params = "doMigrateIn", method = RequestMethod.POST) @ResponseBody public AjaxJson doMigrateIn(HttpServletRequest request, HttpServletResponse response) { String message = null; AjaxJson j = new AjaxJson(); String ls_file = ""; UploadFile uploadFile = new UploadFile(request, ls_file); uploadFile.setCusPath(""); uploadFile.setSwfpath(""); String uploadbasepath = uploadFile.getBasePath();// 文件上传根目录 if (uploadbasepath == null) { uploadbasepath = ResourceUtil.getConfigByName("uploadpath"); } String path = uploadbasepath + File.separator;// 文件保存在硬盘的相对路径 String realPath = uploadFile.getMultipartRequest().getSession() .getServletContext().getRealPath(File.separator) + path;// 文件的硬盘真实路径 message = null; try { File file = new File(realPath); if (!file.exists()) { file.mkdir();// 若目录不存在,创建根目录 } uploadFile.getMultipartRequest().setCharacterEncoding("UTF-8"); MultipartHttpServletRequest multipartRequest = uploadFile .getMultipartRequest(); Map<String, MultipartFile> fileMap = multipartRequest.getFileMap(); String fileName = ""; for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) { MultipartFile mf = entity.getValue();// 获取上传文件对象 fileName = mf.getOriginalFilename();// 获取文件名 String savePath = realPath + fileName; File savefile = new File(savePath); String ls_tmp = savefile.getName(); /*String sqlfilename = realPath + ls_tmp.substring(0, ls_tmp.lastIndexOf(".")) + "\\" + ls_tmp.substring(0, ls_tmp.lastIndexOf(".")) + ".sql";*/ FileCopyUtils.copy(mf.getBytes(), savefile); MigrateForm.unzip(savePath, ""); String sqlFileDir = realPath + ls_tmp.substring(0, ls_tmp.lastIndexOf(".")); File sqlDirFile = new File(sqlFileDir); String sqlfilename = sqlDirFile.getPath() + File.separator; if(sqlDirFile.isDirectory()){ sqlfilename += sqlDirFile.list()[0]; } /*OfficeHtmlUtil officeHtml = new OfficeHtmlUtil(); String sqlStr = officeHtml.getInfo(sqlfilename); String[] sqlStrs = sqlStr.split(";"); for (String exesql : sqlStrs) { if (!StringUtil.isEmpty(exesql) && !"\n".equals(exesql)) { jdbcTemplate.execute(exesql); } }*/ XStream xStream = new XStream(); xStream.processAnnotations(DBTable.class); @SuppressWarnings("unchecked") List<DBTable> dbTables = (List<DBTable>) xStream.fromXML(new File(sqlfilename)); if(!dbTables.isEmpty() && dbTables.size()>0){ for (DBTable dbTable : dbTables) { mergeMigrateInComponent(dbTable); } } } } catch (Exception e1) { e1.printStackTrace(); LogUtil.error(e1.toString()); message = e1.toString(); } logger.info("["+IpUtil.getIpAddr(request)+"][online表单配置导入]"+message); if (StringUtil.isNotEmpty(message)) j.setMsg("SQL文件导入失败," + message); else j.setMsg("SQL文件导入成功"); return j; }
Example 16
Source File: ExcelTempletController.java From jeewx with Apache License 2.0 | 4 votes |
/** * 上传模版数据 * @param request * @param response * @return */ @RequestMapping(params = "importExcel", method = RequestMethod.POST) @ResponseBody @SuppressWarnings("all") public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) { String message = "上传成功"; AjaxJson j = new AjaxJson(); String configId = request.getParameter("tableName"); String jversion = cgFormFieldService.getCgFormVersionByTableName(configId); Map<String, Object> configs = configService.queryConfigs(configId,jversion); //数据库中版本号 String version = (String)configs.get(CgAutoListConstant.CONFIG_VERSION); List<CgFormFieldEntity> lists = (List<CgFormFieldEntity>) configs.get(CgAutoListConstant.FILEDS); MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; Map<String, MultipartFile> fileMap = multipartRequest.getFileMap(); for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) { MultipartFile file = entity.getValue();// 获取上传文件对象 //上传文件的版本号 String docVersion = getDocVersion(file.getOriginalFilename()); if (docVersion.equals(version)) { List<Map<String, Object>> listDate; try { //读取excel模版数据 listDate = (List<Map<String, Object>>) ExcelTempletService.importExcelByIs(file.getInputStream(), lists); if (listDate==null) { message = "识别模版数据错误"; logger.error(message); }else{ for (Map<String, Object> map : listDate) { map.put("id", UUIDGenerator.generate()); int num = dataBaseService.insertTable(configId, map); } message = "文件导入成功!"; } } catch (IOException e) { message = "文件导入失败!"; logger.error(ExceptionUtil.getExceptionMessage(e)); } }else{ message = "模版文件版本和表达不匹配,请重新下载模版"; logger.error(message); } } j.setMsg(message); return j; }
Example 17
Source File: CommonsMultipartResolverTests.java From spring4-understanding with Apache License 2.0 | 4 votes |
private void doTestFiles(MultipartHttpServletRequest request) throws IOException { Set<String> fileNames = new HashSet<String>(); Iterator<String> fileIter = request.getFileNames(); while (fileIter.hasNext()) { fileNames.add(fileIter.next()); } assertEquals(3, fileNames.size()); assertTrue(fileNames.contains("field1")); assertTrue(fileNames.contains("field2")); assertTrue(fileNames.contains("field2x")); CommonsMultipartFile file1 = (CommonsMultipartFile) request.getFile("field1"); CommonsMultipartFile file2 = (CommonsMultipartFile) request.getFile("field2"); CommonsMultipartFile file2x = (CommonsMultipartFile) request.getFile("field2x"); Map<String, MultipartFile> fileMap = request.getFileMap(); assertEquals(3, fileMap.size()); assertTrue(fileMap.containsKey("field1")); assertTrue(fileMap.containsKey("field2")); assertTrue(fileMap.containsKey("field2x")); assertEquals(file1, fileMap.get("field1")); assertEquals(file2, fileMap.get("field2")); assertEquals(file2x, fileMap.get("field2x")); MultiValueMap<String, MultipartFile> multiFileMap = request.getMultiFileMap(); assertEquals(3, multiFileMap.size()); assertTrue(multiFileMap.containsKey("field1")); assertTrue(multiFileMap.containsKey("field2")); assertTrue(multiFileMap.containsKey("field2x")); List<MultipartFile> field1Files = multiFileMap.get("field1"); assertEquals(2, field1Files.size()); assertTrue(field1Files.contains(file1)); assertEquals(file1, multiFileMap.getFirst("field1")); assertEquals(file2, multiFileMap.getFirst("field2")); assertEquals(file2x, multiFileMap.getFirst("field2x")); assertEquals("type1", file1.getContentType()); assertEquals("type2", file2.getContentType()); assertEquals("type2", file2x.getContentType()); assertEquals("field1.txt", file1.getOriginalFilename()); assertEquals("field2.txt", file2.getOriginalFilename()); assertEquals("field2x.txt", file2x.getOriginalFilename()); assertEquals("text1", new String(file1.getBytes())); assertEquals("text2", new String(file2.getBytes())); assertEquals(5, file1.getSize()); assertEquals(5, file2.getSize()); assertTrue(file1.getInputStream() instanceof ByteArrayInputStream); assertTrue(file2.getInputStream() instanceof ByteArrayInputStream); File transfer1 = new File("C:/transfer1"); file1.transferTo(transfer1); File transfer2 = new File("C:/transfer2"); file2.transferTo(transfer2); assertEquals(transfer1, ((MockFileItem) file1.getFileItem()).writtenFile); assertEquals(transfer2, ((MockFileItem) file2.getFileItem()).writtenFile); }
Example 18
Source File: FileUploadUtil.java From ExamStack with GNU General Public License v2.0 | 4 votes |
public static List<String> uploadImg(HttpServletRequest request, HttpServletResponse response, String username) throws Exception{ List<String> filePathList = new ArrayList<String>(); String strPath = ",webapps,files,question," + username; String filepath = System.getProperty("catalina.base") + strPath.replace(',', File.separatorChar); MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; Map<String, MultipartFile> fileMap = multipartRequest.getFileMap(); String fileName = null; for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) { MultipartFile mf = entity.getValue(); fileName = mf.getOriginalFilename(); String file_type = fileName.substring(fileName.indexOf('.')); if(!".jpg".equals(file_type.toLowerCase()) && !".png".equals(file_type.toLowerCase())) throw new Exception("文件类型错误"); fileName = String.valueOf(new Date().getTime()) + file_type; String newfilepath; newfilepath = filepath + File.separatorChar + fileName; String filepathUrl = "files" + File.separatorChar + "question" + File.separatorChar + username + File.separatorChar + fileName; System.out.println("newfilepath=" + newfilepath); File dest = new File(filepath); if(!dest.exists()){ dest.mkdirs(); } File uploadFile = new File(newfilepath); if(uploadFile.exists()){ uploadFile.delete(); } try { log.info("start upload file: " + fileName); FileCopyUtils.copy(mf.getBytes(), uploadFile); } catch (IOException e) { // TODO Auto-generated catch block // e.printStackTrace(); log.info("upload failed. filename: " + fileName + e.getMessage()); return null; } filePathList.add(filepathUrl); } return filePathList; }
Example 19
Source File: CommonsMultipartResolverTests.java From spring-analysis-note with MIT License | 4 votes |
private void doTestFiles(MultipartHttpServletRequest request) throws IOException { Set<String> fileNames = new HashSet<>(); Iterator<String> fileIter = request.getFileNames(); while (fileIter.hasNext()) { fileNames.add(fileIter.next()); } assertEquals(3, fileNames.size()); assertTrue(fileNames.contains("field1")); assertTrue(fileNames.contains("field2")); assertTrue(fileNames.contains("field2x")); CommonsMultipartFile file1 = (CommonsMultipartFile) request.getFile("field1"); CommonsMultipartFile file2 = (CommonsMultipartFile) request.getFile("field2"); CommonsMultipartFile file2x = (CommonsMultipartFile) request.getFile("field2x"); Map<String, MultipartFile> fileMap = request.getFileMap(); assertEquals(3, fileMap.size()); assertTrue(fileMap.containsKey("field1")); assertTrue(fileMap.containsKey("field2")); assertTrue(fileMap.containsKey("field2x")); assertEquals(file1, fileMap.get("field1")); assertEquals(file2, fileMap.get("field2")); assertEquals(file2x, fileMap.get("field2x")); MultiValueMap<String, MultipartFile> multiFileMap = request.getMultiFileMap(); assertEquals(3, multiFileMap.size()); assertTrue(multiFileMap.containsKey("field1")); assertTrue(multiFileMap.containsKey("field2")); assertTrue(multiFileMap.containsKey("field2x")); List<MultipartFile> field1Files = multiFileMap.get("field1"); assertEquals(2, field1Files.size()); assertTrue(field1Files.contains(file1)); assertEquals(file1, multiFileMap.getFirst("field1")); assertEquals(file2, multiFileMap.getFirst("field2")); assertEquals(file2x, multiFileMap.getFirst("field2x")); assertEquals("type1", file1.getContentType()); assertEquals("type2", file2.getContentType()); assertEquals("type2", file2x.getContentType()); assertEquals("field1.txt", file1.getOriginalFilename()); assertEquals("field2.txt", file2.getOriginalFilename()); assertEquals("field2x.txt", file2x.getOriginalFilename()); assertEquals("text1", new String(file1.getBytes())); assertEquals("text2", new String(file2.getBytes())); assertEquals(5, file1.getSize()); assertEquals(5, file2.getSize()); assertTrue(file1.getInputStream() instanceof ByteArrayInputStream); assertTrue(file2.getInputStream() instanceof ByteArrayInputStream); File transfer1 = new File("C:/transfer1"); file1.transferTo(transfer1); File transfer2 = new File("C:/transfer2"); file2.transferTo(transfer2); assertEquals(transfer1, ((MockFileItem) file1.getFileItem()).writtenFile); assertEquals(transfer2, ((MockFileItem) file2.getFileItem()).writtenFile); }
Example 20
Source File: EgovFileMngUtil.java From oslits with GNU General Public License v3.0 | 3 votes |
/** * 파일 업로드 처리 * @param request MultipartHttpServletRequest content-type:multipart/form-data 필수 * @return 파일첨부 완료시 atchFileId값 리턴 * 에러 발생 시 'ERROR' 리턴 * 첨부하려는 파일이 없을 경우 'NULL' 리턴 * @decription * [JSP SCRIPT 설정 시] * dragndropDiv - Drag&Drop (fileUpload.js)를 이용한 파일 첨부 시, 첨부된 파일 목록 DIV의 ID (개별 삭제X, 전체 삭제O) * dragandrophandler - Drag&Drop의 영역을 지정하려는 div의 id값 * egovFileUpload - input type='file'의 id값 * status1 - 파일 선택으로 추가된 파일 목록 (개별 삭제 가능) * [필요 파일] * fileUpload.js * fileUpload.css * EgovMultiFile.js * [필수] * FormData 전송 방식이기 때문에 contentType: multipart/form-data이 기본값 * AJAX에서 contentType: false 로 옵션 설정 필수! * [동작 예] * TextFile1.txt , TextFile2.txt를 동시에 업로드 했다고 가정할 경우 * 두 파일 atchFileId에 OSL000001 부여 * 첨부된 파일 불러오기에는 FILE_SN 값으로 분류한다. TextFile1.txt - file_sn=0, TextFile2.txt - file_sn=1 */ public List<FileVO> fileUploadInsert(MultipartHttpServletRequest request,String inputAtchFileId, int inputFileSn, String addStrPath) throws Exception{ //파일 정보 담을 변수 List<FileVO> _result = null; inputFileSn = (inputFileSn<0)?0:inputFileSn; //첨부된 파일 정보 불러오기 final Map<String, MultipartFile> files = request.getFileMap(); //첨부된 파일이 존재할 경우 if(!files.isEmpty()){ //실제 저장소에 파일을 등록하고 FileVO 리턴 _result = parseFileInf(files, "OSL_", inputFileSn, inputAtchFileId,"",addStrPath); } return _result; }