List of usage examples for org.springframework.web.multipart.commons CommonsMultipartFile getBytes
@Override public byte[] getBytes()
From source file:com.hp.avmon.discovery.service.DiscoveryService.java
/** * MIB/*from w w w .j a v a2 s . c o m*/ * * @param request * @return * @throws IOException */ public String importMibFile(HttpServletRequest request) throws IOException { String result = StringUtil.EMPTY; HashMap<String, ArrayList<Map<String, String>>> resultMap = new HashMap<String, ArrayList<Map<String, String>>>(); ArrayList<Map<String, String>> files = new ArrayList<Map<String, String>>(); String typeId = request.getParameter("typeId"); String deviceName = request.getParameter("deviceName"); String deviceDesc = request.getParameter("deviceDesc"); String factory = request.getParameter("factory"); MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; // ? String templatePath = Config.getInstance().getMibfilesUploadPath(); File dirPath = new File(templatePath); if (!dirPath.exists()) { dirPath.mkdirs(); } Map<String, String> fileMap; for (Iterator<String> it = multipartRequest.getFileNames(); it.hasNext();) { String fileName = (String) it.next(); fileMap = new HashMap<String, String>(); CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile(fileName); if (file != null && file.getSize() != 0) { String sep = System.getProperty("file.separator"); File uploadedFile = new File(dirPath + sep + file.getOriginalFilename()); FileCopyUtils.copy(file.getBytes(), uploadedFile); try { insertMibFileTb(file.getOriginalFilename(), typeId, deviceName, deviceDesc, factory); MibFileParserDB mibFileParser = new MibFileParserDB(dirPath + sep + file.getOriginalFilename()); mibFileParser.parseMib(jdbcTemplate); } catch (MibLoaderException e) { fileMap.put("error", "Mib"); logger.error(e.getMessage()); } catch (DataAccessException e1) { logger.error(e1.getMessage()); fileMap.put("error", "??,?"); } catch (Exception e2) { logger.error(this.getClass().getName() + e2.getMessage()); fileMap.put("error", ",?"); } } fileMap.put("url", ""); fileMap.put("thumbnailUrl", ""); fileMap.put("name", file.getOriginalFilename()); fileMap.put("type", "image/jpeg"); fileMap.put("size", file.getSize() + ""); fileMap.put("deleteUrl", ""); fileMap.put("deleteType", "DELETE"); files.add(fileMap); } resultMap.put("files", files); result = JackJson.fromObjectToJson(resultMap); logger.debug(result); return result; }
From source file:com.eliteams.pay.web.controller.RegisterController.java
@RequestMapping("/uploadmethod") @ResponseBody/*w w w. j a va2 s . c om*/ public String uploadmethod(HttpServletRequest request, HttpServletResponse response) throws IOException { Map<String, Object> rtnMap = new HashMap<String, Object>(); // String urlString = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() // + request.getContextPath() + "/pay/papersPhoto/"; String newRealFileName = null; String ftype = request.getParameter("ftype"); try { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; CommonsMultipartFile file = null; // String filetype = "businessLicense";//? if (ftype != null && !ftype.equals("") && Integer.valueOf(ftype) == 1) { file = (CommonsMultipartFile) multipartRequest.getFile("fileField1"); } if (ftype != null && !ftype.equals("") && Integer.valueOf(ftype) == 2) { file = (CommonsMultipartFile) multipartRequest.getFile("fileField2"); /// filetype = "idCard";//? } if (ftype != null && !ftype.equals("") && Integer.valueOf(ftype) == 3) { file = (CommonsMultipartFile) multipartRequest.getFile("fileField3"); // filetype = "taxRegistration";// } if (ftype != null && !ftype.equals("") && Integer.valueOf(ftype) == 4) { file = (CommonsMultipartFile) multipartRequest.getFile("fileField4"); /// filetype = "proxy";// } if (ftype != null && !ftype.equals("") && Integer.valueOf(ftype) == 5) { file = (CommonsMultipartFile) multipartRequest.getFile("fileField5"); /// filetype = "file53";//? } if (ftype != null && !ftype.equals("") && Integer.valueOf(ftype) == 6) { file = (CommonsMultipartFile) multipartRequest.getFile("fileField6"); // filetype = "file6";//?? } if (file == null) { rtnMap.put("info", ""); return JSONUtil.map2json(rtnMap); } // ?? String realFileName = file.getOriginalFilename(); if (realFileName == null || "".equals(realFileName)) { rtnMap.put("info", ""); return JSONUtil.map2json(rtnMap); } String suffixFlag = realFileName.substring(realFileName.indexOf(".")); suffixFlag = suffixFlag.toLowerCase(); newRealFileName = new Date().getTime() + "." + FilenameUtils.getExtension(realFileName); /** * ???? */ if (!suffixFlag.contains("jpg") && !suffixFlag.contains("bmp") && !suffixFlag.contains("jpeg") && !suffixFlag.contains("gif") && !suffixFlag.contains("tiff") && !suffixFlag.contains("psd") && !suffixFlag.contains("tga") && !suffixFlag.contains("png") && !suffixFlag.contains("eps")) { rtnMap.put("info", "?"); return JSONUtil.map2json(rtnMap); } /** * :? */ byte[] bt = new byte[4]; bt = Arrays.copyOf(file.getBytes(), 4); String str = ImageTypeCheck.getPicType(bt); if (str != null) { if (str.contains("noimg")) { rtnMap.put("info", "???:jpg?jpeg?png?gif?bmp"); return JSONUtil.map2json(rtnMap); } } else { rtnMap.put("info", "?"); return JSONUtil.map2json(rtnMap); } /** *:? ? */ /*Image img= ImageIO.read( file.getInputStream()); img.getWidth(null);*/ // ? // String ctxPath = request.getSession().getServletContext().getRealPath("//") + "//pay//papersPhoto//" + "//"; // // String ctxPath = request.getScheme() + "://" + request.getLocalAddr() + ":" + request.getLocalPort() // + photopath; String ctxPath = realdownloadpath + photopath; logger.info("" + ctxPath); // File dirPath = new File(uploadpath); if (!dirPath.exists()) { dirPath.mkdir(); } File uploadFile = new File(uploadpath + newRealFileName); FileCopyUtils.copy(file.getBytes(), uploadFile); rtnMap.put("info", "?"); rtnMap.put("fileurl", ctxPath + newRealFileName); rtnMap.put("FileName", newRealFileName); // } } catch (Exception e) { e.printStackTrace(); logger.error(" ", e); rtnMap.put("info", ""); } return JSONUtil.map2json(rtnMap); }
From source file:org.springframework.web.multipart.commons.CommonsMultipartResolverTests.java
private void doTestFiles(MultipartHttpServletRequest request) throws IOException { Set<String> fileNames = new HashSet<>(); Iterator<String> fileIter = request.getFileNames(); while (fileIter.hasNext()) { fileNames.add(fileIter.next());//from www.ja va 2 s . c o m } 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); }
From source file:org.springframework.web.multipart.commons.CommonsMultipartResolverTests.java
private void doTestBinding(MockCommonsMultipartResolver resolver, MockHttpServletRequest originalRequest, MultipartHttpServletRequest request) throws UnsupportedEncodingException { MultipartTestBean1 mtb1 = new MultipartTestBean1(); assertArrayEquals(null, mtb1.getField1()); assertEquals(null, mtb1.getField2()); ServletRequestDataBinder binder = new ServletRequestDataBinder(mtb1, "mybean"); binder.registerCustomEditor(byte[].class, new ByteArrayMultipartFileEditor()); binder.bind(request);/* ww w .j a v a 2s . co m*/ List<MultipartFile> file1List = request.getFiles("field1"); CommonsMultipartFile file1a = (CommonsMultipartFile) file1List.get(0); CommonsMultipartFile file1b = (CommonsMultipartFile) file1List.get(1); CommonsMultipartFile file2 = (CommonsMultipartFile) request.getFile("field2"); assertEquals(file1a, mtb1.getField1()[0]); assertEquals(file1b, mtb1.getField1()[1]); assertEquals(new String(file2.getBytes()), new String(mtb1.getField2())); MultipartTestBean2 mtb2 = new MultipartTestBean2(); assertArrayEquals(null, mtb2.getField1()); assertEquals(null, mtb2.getField2()); binder = new ServletRequestDataBinder(mtb2, "mybean"); binder.registerCustomEditor(String.class, "field1", new StringMultipartFileEditor()); binder.registerCustomEditor(String.class, "field2", new StringMultipartFileEditor("UTF-16")); binder.bind(request); assertEquals(new String(file1a.getBytes()), mtb2.getField1()[0]); assertEquals(new String(file1b.getBytes()), mtb2.getField1()[1]); assertEquals(new String(file2.getBytes(), "UTF-16"), mtb2.getField2()); resolver.cleanupMultipart(request); assertTrue(((MockFileItem) file1a.getFileItem()).deleted); assertTrue(((MockFileItem) file1b.getFileItem()).deleted); assertTrue(((MockFileItem) file2.getFileItem()).deleted); resolver.setEmpty(true); request = resolver.resolveMultipart(originalRequest); binder.setBindEmptyMultipartFiles(false); String firstBound = mtb2.getField2(); binder.bind(request); assertFalse(mtb2.getField2().isEmpty()); assertEquals(firstBound, mtb2.getField2()); request = resolver.resolveMultipart(originalRequest); binder.setBindEmptyMultipartFiles(true); binder.bind(request); assertTrue(mtb2.getField2().isEmpty()); }
From source file:org.webcurator.ui.tools.controller.TreeToolController.java
@SuppressWarnings("unchecked") @Override/*from ww w.j a v a 2 s .c om*/ protected ModelAndView handle(HttpServletRequest req, HttpServletResponse res, Object comm, BindException errors) throws Exception { TreeToolCommand command = (TreeToolCommand) comm; TargetInstance ti = (TargetInstance) req.getSession().getAttribute("sessionTargetInstance"); // If the tree is not loaded then load the tree into session // data and then load any AQA 'importable items' into session data. if (command.getLoadTree() != null) { // load the tree.. log.info("Generating Tree"); HarvestResourceNodeTreeBuilder treeBuilder = qualityReviewFacade .getHarvestResultTree(command.getLoadTree()); WCTNodeTree tree = treeBuilder.getTree(); req.getSession().setAttribute("tree", tree); command.setHrOid(command.getLoadTree()); log.info("Tree complete"); if (autoQAUrl != null && autoQAUrl.length() > 0) { List<AQAElement> candidateElements = new ArrayList<AQAElement>(); // load AQA 'importable items' (if any).. File xmlFile; try { xmlFile = harvestLogManager.getLogfile(ti, command.getLogFileName()); } catch (Exception e) { xmlFile = null; log.info("Missing AQA report file: " + command.getLogFileName()); } if (xmlFile != null) { Document aqaResult = readXMLDocument(xmlFile); NodeList parentElementsNode = aqaResult.getElementsByTagName("missingElements"); if (parentElementsNode.getLength() > 0) { NodeList elementNodes = ((Element) parentElementsNode.item(0)) .getElementsByTagName("element"); for (int i = 0; i < elementNodes.getLength(); i++) { Element element = (Element) elementNodes.item(i); if (element.getAttribute("statuscode").equals("200")) { candidateElements.add(new AQAElement(element.getAttribute("url"), element.getAttribute("contentfile"), element.getAttribute("contentType"), Long.parseLong(element.getAttribute("contentLength")))); } } } req.getSession().setAttribute("aqaImports", candidateElements); } } } // Load the tree items from the session. WCTNodeTree tree = (WCTNodeTree) req.getSession().getAttribute("tree"); List<AQAElement> imports = (List<AQAElement>) req.getSession().getAttribute("aqaImports"); // Go back to the page if there were validation errors. if (errors.hasErrors()) { ModelAndView mav = new ModelAndView(getSuccessView()); mav.addObject("tree", tree); mav.addObject("command", command); mav.addObject("aqaImports", imports); mav.addObject(Constants.GBL_ERRORS, errors); if (autoQAUrl != null && autoQAUrl.length() > 0) { mav.addObject("showAQAOption", 1); } else { mav.addObject("showAQAOption", 0); } return mav; } // Handle any tree actions. else if (command.isAction(TreeToolCommand.ACTION_TREE_ACTION)) { // If we are toggling things open/closed.. if (command.getToggleId() != null) { tree.toggle(command.getToggleId()); } // if we're pruning.. if (command.getMarkForDelete() != null) { tree.markForDelete(command.getMarkForDelete(), command.getPropagateDelete()); } // if we're importing single items.. if (command.getTargetURL() != null) { HarvestResourceNodeTreeBuilder tb = new HarvestResourceNodeTreeBuilder(); try { URL parentUrl = tb.getParent(new URL(command.getTargetURL())); } catch (MalformedURLException me) { errors.reject("tools.errors.invalidtargeturl"); ModelAndView mav = new ModelAndView(getSuccessView()); mav.addObject("tree", tree); mav.addObject("command", command); mav.addObject("aqaImports", imports); mav.addObject(Constants.GBL_ERRORS, errors); if (autoQAUrl != null && autoQAUrl.length() > 0) { mav.addObject("showAQAOption", 1); } else { mav.addObject("showAQAOption", 0); } return mav; } if (command.getImportType().equals(TreeToolCommand.IMPORT_FILE)) { // We're importing a file from the user's file system, uploaded // via their browser. We need to store the file so it can be added // to the archive when the SAVE command is eventually issued. // We also need to add a node to the tree-view in such a way that the // user can distinguish imported files from pruned files and // original files. MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) req; CommonsMultipartFile uploadedFile = (CommonsMultipartFile) multipartRequest .getFile("sourceFile"); // save uploaded file as tempFileName in configured uploadedFilesDir String tempFileName = UUID.randomUUID().toString(); File xfrFile = new File(uploadedFilesDir + tempFileName); StringBuffer buf = new StringBuffer(); buf.append("HTTP/1.1 200 OK\n"); buf.append("Content-Type: "); buf.append(uploadedFile.getContentType() + "\n"); buf.append("Content-Length: "); buf.append(uploadedFile.getSize() + "\n"); buf.append("Connection: close\n\n"); FileOutputStream fos = new FileOutputStream(xfrFile); fos.write(buf.toString().getBytes()); fos.write(uploadedFile.getBytes()); fos.close(); tree.insert(command.getTargetURL(), xfrFile.length(), tempFileName, uploadedFile.getContentType()); } if (command.getImportType().equals(TreeToolCommand.IMPORT_URL)) { // We're importing a file via a URL that the user has specified, we // need to use the URL to do a HTTP GET and store the resultant // down-loaded file so it can be added to the archive when the // SAVE command is eventually issued. // We also need to add a node to the tree-view in such a way that the // user can distinguish imported files from pruned files and // original files. // save uploaded file as tempFileName in configured uploadedFilesDir String tempFileName = UUID.randomUUID().toString(); File xfrFile = new File(uploadedFilesDir + tempFileName); FileOutputStream fos = new FileOutputStream(xfrFile); //String contentType = null; String outStrings[] = new String[1]; try { fos.write(fetchHTTPResponse(command.getSourceURL(), outStrings)); } catch (HTTPGetException ge) { errors.reject("tools.errors.httpgeterror", new Object[] { command.getSourceURL(), ge.getMessage() }, ""); ModelAndView mav = new ModelAndView(getSuccessView()); mav.addObject("tree", tree); mav.addObject("aqaImports", imports); mav.addObject("command", command); mav.addObject(Constants.GBL_ERRORS, errors); if (autoQAUrl != null && autoQAUrl.length() > 0) { mav.addObject("showAQAOption", 1); } else { mav.addObject("showAQAOption", 0); } return mav; } finally { fos.close(); } tree.insert(command.getTargetURL(), xfrFile.length(), tempFileName, outStrings[0]); } } ModelAndView mav = new ModelAndView(getSuccessView()); mav.addObject("tree", tree); mav.addObject("aqaImports", imports); mav.addObject("command", command); if (autoQAUrl != null && autoQAUrl.length() > 0) { mav.addObject("showAQAOption", 1); } else { mav.addObject("showAQAOption", 0); } return mav; } // Handle browse action. else if (command.isAction(TreeToolCommand.ACTION_VIEW)) { HarvestResource resource = tree.getNodeCache().get(command.getSelectedRow()).getSubject(); Long resultOid = resource.getResult().getOid(); String url = resource.getName(); if (enableAccessTool && harvestResourceUrlMapper != null) { return new ModelAndView("redirect:" + harvestResourceUrlMapper.generateUrl(resource.getResult(), resource.buildDTO())); } else { return new ModelAndView("redirect:/curator/tools/browse/" + resultOid + "/" + url); } } // Handle show hop path action. else if (command.isAction(TreeToolCommand.ACTION_SHOW_HOP_PATH)) { TargetInstance tinst = (TargetInstance) req.getSession().getAttribute("sessionTargetInstance"); Long instanceOid = tinst.getOid(); String url = command.getSelectedUrl(); return new ModelAndView("redirect:/curator/target/show-hop-path.html?targetInstanceOid=" + instanceOid + "&logFileName=sortedcrawl.log&url=" + url); } // handle import of one or more AQA items.. else if (command.isAction(TreeToolCommand.IMPORT_AQA_FILE)) { // iterate over the selected (checked) items.. if (command.getAqaImports() != null) { List<AQAElement> removeElements = new ArrayList<AQAElement>(); String[] aqaImportUrls = command.getAqaImports(); for (int i = 0; i < aqaImportUrls.length; i++) { String aqaUrl = aqaImportUrls[i]; for (Iterator iter = imports.iterator(); iter.hasNext();) { AQAElement elem = (AQAElement) iter.next(); if (elem.getUrl().equals(aqaUrl)) { // We're importing a missing file, captured by the AQA process. // We need to store the file with HTTP header info so it can be added // to the archive when the SAVE command is eventually issued. // We also need to add a node to the tree-view in such a way that the // user can distinguish imported files from pruned files and // original files. File aqaFile = null; try { aqaFile = harvestLogManager.getLogfile(ti, elem.getContentFile()); // save imported file using a random tempFileName in configured uploadedFilesDir String tempFileName = UUID.randomUUID().toString(); File xfrFile = new File(uploadedFilesDir + tempFileName); StringBuffer buf = new StringBuffer(); buf.append("HTTP/1.1 200 OK\n"); buf.append("Content-Type: "); buf.append(elem.getContentType() + "\n"); buf.append("Content-Length: "); buf.append(elem.getContentLength() + "\n"); buf.append("Connection: close\n\n"); FileOutputStream fos = new FileOutputStream(xfrFile); fos.write(buf.toString().getBytes()); FileInputStream fin = new FileInputStream(aqaFile); byte[] bytes = new byte[8192]; int len = 0; while ((len = fin.read(bytes)) >= 0) { fos.write(bytes, 0, len); } fos.close(); fin.close(); tree.insert(aqaUrl, xfrFile.length(), tempFileName, elem.getContentType()); removeElements.add(elem); } catch (Exception e) { log.info("Missing AQA import file: " + elem.getContentFile()); } } } } ; //end for for (Iterator remit = removeElements.iterator(); remit.hasNext();) { AQAElement rem = (AQAElement) remit.next(); imports.remove(rem); } } ; ModelAndView mav = new ModelAndView(getSuccessView()); mav.addObject("tree", tree); mav.addObject("aqaImports", imports); mav.addObject("command", command); if (autoQAUrl != null && autoQAUrl.length() > 0) { mav.addObject("showAQAOption", 1); } else { mav.addObject("showAQAOption", 0); } return mav; } // Handle the save action. else if (command.isAction(TreeToolCommand.ACTION_SAVE)) { List<String> uris = new LinkedList<String>(); for (WCTNode node : tree.getPrunedNodes()) { if (node.getSubject() != null) { uris.add(node.getSubject().getName()); } } List<HarvestResourceDTO> hrs = new LinkedList<HarvestResourceDTO>(); for (HarvestResourceDTO dto : tree.getImportedNodes()) { hrs.add(dto); } HarvestResult result = qualityReviewFacade.copyAndPrune(command.getHrOid(), uris, hrs, command.getProvenanceNote(), tree.getModificationNotes()); // Make sure that the tree is removed from memory. removeTree(req); removeAQAImports(req); return new ModelAndView("redirect:/" + Constants.CNTRL_TI + "?targetInstanceId=" + result.getTargetInstance().getOid() + "&cmd=edit&init_tab=RESULTS"); } else if (command.isAction(TreeToolCommand.ACTION_CANCEL)) { // Make sure that objects removed from memory. removeTree(req); removeAQAImports(req); TargetInstance tinst = (TargetInstance) req.getSession().getAttribute("sessionTargetInstance"); return new ModelAndView("redirect:/curator/target/quality-review-toc.html?targetInstanceOid=" + tinst.getOid() + "&harvestResultId=" + command.getHrOid()); } // Handle an unknown action? else { ModelAndView mav = new ModelAndView(getSuccessView()); mav.addObject("tree", tree); mav.addObject("command", command); mav.addObject("aqaImports", imports); mav.addObject(Constants.GBL_ERRORS, errors); if (autoQAUrl != null && autoQAUrl.length() > 0) { mav.addObject("showAQAOption", 1); } else { mav.addObject("showAQAOption", 0); } return mav; } }