List of usage examples for org.springframework.web.multipart MultipartFile getInputStream
@Override
InputStream getInputStream() throws IOException;
From source file:com.dlshouwen.wzgl.content.controller.ArticleController.java
/** * //from w w w .j av a2 s . c om * * @param album * @param bindingResult * @return ajax? * @throws Exception */ @RequestMapping(value = "/editAlbum", method = RequestMethod.POST) public void editArtAlbum(@Valid Album album, HttpServletRequest request, BindingResult bindingResult, HttpServletResponse response) throws Exception { // AJAX? AjaxResponse ajaxResponse = new AjaxResponse(); // ?? if (bindingResult.hasErrors()) { ajaxResponse.bindingResultHandler(bindingResult); // ? LogUtils.updateOperationLog(request, OperationType.UPDATE, "id" + album.getAlbum_id() + "??" + album.getAlbum_name() + "?" + AjaxResponse.getBindingResultMessage(bindingResult) + ""); response.setContentType("text/html;charset=utf-8"); JSONObject obj = JSONObject.fromObject(ajaxResponse); response.getWriter().write(obj.toString()); return; } MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; MultipartFile multipartFile = multipartRequest.getFile("picture"); String fileName = multipartFile.getOriginalFilename(); //? String path = null; if (null != multipartFile && StringUtils.isNotEmpty(multipartFile.getOriginalFilename())) { JSONObject jobj = FileUploadClient.upFile(request, multipartFile.getOriginalFilename(), multipartFile.getInputStream()); if (jobj.getString("responseMessage").equals("OK")) { path = jobj.getString("fpath"); } } /* if (fileName.trim().length() > 0) { int pos = fileName.lastIndexOf("."); fileName = fileName.substring(pos); String fileDirPath = request.getSession().getServletContext().getRealPath("/"); String path = fileDirPath.substring(0, fileDirPath.lastIndexOf(File.separator)) + CONFIG.UPLOAD_PIC_PATH; Date date = new Date(); fileName = String.valueOf(date.getTime()) + fileName; File file = new File(path); if (!file.exists()) { file.mkdirs(); } file = new File(path + "/" + fileName); if (!file.exists()) { file.createNewFile(); } path = path + "/" + fileName; FileOutputStream fos = null; InputStream s = null; try { fos = new FileOutputStream(file); s = multipartFile.getInputStream(); byte[] buffer = new byte[1024]; int read = 0; while ((read = s.read(buffer)) != -1) { fos.write(buffer, 0, read); } fos.flush(); } catch (Exception e) { e.printStackTrace(); } finally { if (fos != null) { fos.close(); } if (s != null) { s.close(); } } path = path.replaceAll("\\\\", "/"); album.setAlbum_coverpath(path); } */ if (null != path) { album.setAlbum_coverpath(path); } // ???? Date nowDate = new Date(); // ? album.setAlbum_updatedate(nowDate); album.setAlbum_flag("1"); // albumDao.updateAlbum(album); // ???? ajaxResponse.setSuccess(true); ajaxResponse.setSuccessMessage("??"); //URL?? Map map = new HashMap(); map.put("URL", "wzgl/article/article"); ajaxResponse.setExtParam(map); // ? LogUtils.updateOperationLog(request, OperationType.UPDATE, "id" + album.getAlbum_id() + "??" + album.getAlbum_name()); response.setContentType("text/html;charset=utf-8"); JSONObject obj = JSONObject.fromObject(ajaxResponse); response.getWriter().write(obj.toString()); }
From source file:com.eryansky.modules.disk.service.DiskManager.java
/** * //from ww w. j a va 2 s . com * @param sessionInfo * @param folder * @param uploadFile * @throws Exception */ public File fileUpload(SessionInfo sessionInfo, Folder folder, MultipartFile uploadFile) throws Exception { File file = null; /* Exception exception = null; */ java.io.File tempFile = null; try { String relativeDir = DiskUtils.getRelativePath(folder, sessionInfo.getUserId()); String fullName = uploadFile.getOriginalFilename(); String code = FileUploadUtils.encodingFilenamePrefix(sessionInfo.getUserId().toString(), fullName); String storePath = iFileManager.getStorePath(folder, sessionInfo.getUserId(), uploadFile.getOriginalFilename()); String fileTemp = AppConstants.getDiskTempDir() + java.io.File.separator + code; tempFile = new java.io.File(fileTemp); FileOutputStream fos = FileUtils.openOutputStream(tempFile); IOUtils.copy(uploadFile.getInputStream(), fos); iFileManager.saveFile(storePath, fileTemp, false); file = new File(); file.setFolder(folder); file.setCode(code); file.setUserId(sessionInfo.getUserId()); file.setName(fullName); file.setFilePath(storePath); file.setFileSize(uploadFile.getSize()); file.setFileSuffix(FilenameUtils.getExtension(fullName)); fileManager.save(file); } catch (Exception e) { // exception = e; throw new ServiceException(DiskUtils.UPLOAD_FAIL_MSG + e.getMessage(), e); } finally { // if (exception != null && file != null) { // DiskUtils.deleteFile(null, file.getId()); // } if (tempFile != null && tempFile.exists()) { tempFile.delete(); } } return file; }
From source file:de.topicmapslab.majortom.server.topicmaps.TopicMapsHandler.java
/** * {@inheritDoc}// w w w.j av a 2 s . c om */ @Override public void loadFromFileUpload(String id, final MultipartFile file) { logger.info("Start Loading file: " + file.getOriginalFilename()); final TopicMap topicMap = (TopicMap) topicMapMap.get(id); if (topicMap == null) return; if (file.getOriginalFilename().length() == 0) return; if (((ITopicMap) topicMap).getStore() instanceof InMemoryTopicMapStore) { InMemoryTopicMapStore store = (InMemoryTopicMapStore) ((ITopicMap) topicMap).getStore(); try { if (file.getOriginalFilename().toLowerCase().endsWith("xtm")) { Importer.importStream(store, file.getInputStream(), topicMap.getLocator().toExternalForm(), Format.XTM); } else if (file.getOriginalFilename().toLowerCase().endsWith("ctm")) { Importer.importStream(store, file.getInputStream(), topicMap.getLocator().toExternalForm(), Format.CTM); } else { throw new IllegalArgumentException("Only XTM or CTM files allowed."); } logger.info("Finished Loading file: " + file.getOriginalFilename()); logger.info("Start removing duplicates"); ((ITopicMap) topicMap).removeDuplicates(); logger.info("Finished removing duplicates"); // indexing stuff indexTopicMap(topicMap); } catch (Exception e) { throw new IllegalArgumentException("Only XTM or CTM files allowed.", e); } return; } try { TopicMapReader reader = null; if (file.getOriginalFilename().toLowerCase().endsWith("xtm")) { reader = new XTMTopicMapReader(topicMap, file.getInputStream(), topicMap.getLocator().toExternalForm()); } else if (file.getOriginalFilename().toLowerCase().endsWith("ctm")) { reader = new CTMTopicMapReader(topicMap, file.getInputStream(), topicMap.getLocator().toExternalForm()); } else { throw new IllegalArgumentException("Only XTM or CTM files allowed."); } reader.read(); logger.info("Start removing duplicates"); ((ITopicMap) topicMap).removeDuplicates(); logger.info("Finished removing duplicates"); logger.info("Finished Loading file: " + file.getOriginalFilename()); } catch (IOException e) { logger.error("Could not load topic map", e); } }
From source file:com.teasoft.teavote.controller.ElectionInfoController.java
@RequestMapping(value = "api/teavote/election-info", method = RequestMethod.POST) @ResponseBody/*w w w .j ava2s. co m*/ public JSONResponse saveElectionInfo(@RequestParam("logo") MultipartFile file, @RequestParam("commissioner") String commissioner, @RequestParam("orgName") String orgName, @RequestParam("electionDate") String electionDate, @RequestParam("startTime") String startTime, @RequestParam("endTime") String endTime, @RequestParam("pollingStation") String pollingStation, @RequestParam("startTimeInMillis") String startTimeInMillis, @RequestParam("endTimeInMillis") String endTimeInMillis, HttpServletRequest request) throws Exception { JSONResponse jSONResponse = new JSONResponse(); //Candidate candidate = new Candidate(); Map<String, String> errorMessages = new HashMap<>(); if (!file.isEmpty()) { BufferedImage image = ImageIO.read(file.getInputStream()); Integer width = image.getWidth(); Integer height = image.getHeight(); if (Math.abs(width - height) > MAX_IMAGE_DIM_DIFF) { errorMessages.put("image", "Invalid Image Dimension - Max abs(Width - height) must be 50 or less"); } else { //Resize image BufferedImage originalImage = ImageIO.read(file.getInputStream()); int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType(); BufferedImage resizeImagePng = resizeImage(originalImage, type); ConfigLocation configLocation = new ConfigLocation(); //String rootPath = request.getSession().getServletContext().getRealPath("/"); File serverFile = new File(configLocation.getConfigPath() + File.separator + "teavote-logo.jpg"); switch (file.getContentType()) { case "image/png": ImageIO.write(resizeImagePng, "png", serverFile); break; case "image/jpeg": ImageIO.write(resizeImagePng, "jpg", serverFile); break; default: ImageIO.write(resizeImagePng, "png", serverFile); break; } } } else { // errorMessages.put("image", "File Empty"); } //Load properties Properties prop = appProp.getProperties(); ConfigLocation configLocation = new ConfigLocation(); prop.load(configLocation.getExternalProperties()); prop.setProperty("teavote.orgName", orgName); prop.setProperty("teavote.commissioner", commissioner); prop.setProperty("teavote.electionDate", electionDate); prop.setProperty("teavote.startTime", startTime); prop.setProperty("teavote.endTime", endTime); prop.setProperty("teavote.pollingStation", pollingStation); prop.setProperty("teavote.startTimeInMillis", startTimeInMillis); prop.setProperty("teavote.endTimeInMillis", endTimeInMillis); File f = new File(configLocation.getConfigPath() + File.separator + "application.properties"); OutputStream out = new FileOutputStream(f); DefaultPropertiesPersister p = new DefaultPropertiesPersister(); p.store(prop, out, "Header Comment"); if (errorMessages.isEmpty()) { return new JSONResponse(true, 0, null, Enums.JSONResponseMessage.SUCCESS.toString()); } return new JSONResponse(false, 0, errorMessages, Enums.JSONResponseMessage.SERVER_ERROR.toString()); }
From source file:it.smartcommunitylab.climb.contextstore.controller.ChildController.java
@RequestMapping(value = "/api/image/upload/png/{ownerId}/{objectId}", method = RequestMethod.POST) public @ResponseBody String uploadImage(@RequestParam("file") MultipartFile file, @PathVariable String ownerId, @PathVariable String objectId, HttpServletRequest request) throws Exception { Criteria criteria = Criteria.where("objectId").is(objectId); Child child = storage.findOneData(Child.class, criteria, ownerId); if (!validateAuthorizationByExp(ownerId, child.getInstituteId(), child.getSchoolId(), null, "ALL", request)) {/*w w w. j av a 2 s. co m*/ throw new UnauthorizedException("Unauthorized Exception: token not valid"); } String name = objectId + ".png"; if (logger.isInfoEnabled()) { logger.info("uploadImage:" + name); } if (!file.isEmpty()) { BufferedOutputStream stream = new BufferedOutputStream( new FileOutputStream(new File(imageUploadDir + "/" + name))); FileCopyUtils.copy(file.getInputStream(), stream); stream.close(); } return "{\"status\":\"OK\"}"; }
From source file:com.dlshouwen.wzgl.picture.controller.PictureController.java
/** * //from w w w.jav a 2 s. co m * * @param picture * @param bindingResult ? * @param request * @return ajax? * @throws Exception */ @RequestMapping(value = "/ajaxAdd", method = RequestMethod.POST) public void ajaxAddPicture(@Valid Picture picture, BindingResult bindingResult, HttpServletRequest request, HttpServletResponse response) throws Exception { // AJAX? AjaxResponse ajaxResponse = new AjaxResponse(); // ??zz if (bindingResult.hasErrors()) { ajaxResponse.bindingResultHandler(bindingResult); //? Map map = new HashMap(); map.put("URL", basePath + "picture"); ajaxResponse.setExtParam(map); // ? LogUtils.updateOperationLog(request, OperationType.INSERT, "???" + AjaxResponse.getBindingResultMessage(bindingResult) + ""); response.setContentType("text/html;charset=utf-8"); JSONObject obj = JSONObject.fromObject(ajaxResponse); response.getWriter().write(obj.toString()); return; } MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; MultipartFile multipartFile = multipartRequest.getFile("picture"); String fileName = multipartFile.getOriginalFilename(); //? String path = null; if (null != multipartFile && StringUtils.isNotEmpty(multipartFile.getOriginalFilename())) { JSONObject jobj = FileUploadClient.upFile(request, fileName, multipartFile.getInputStream()); if (jobj.getString("responseMessage").equals("OK")) { path = jobj.getString("fpath"); } } /* int pos = fileName.lastIndexOf("."); fileName = fileName.substring(pos); String fileDirPath = request.getSession().getServletContext().getRealPath("/"); String path = fileDirPath.substring(0, fileDirPath.lastIndexOf(File.separator)) + CONFIG.UPLOAD_PIC_PATH; Date date = new Date(); fileName = String.valueOf(date.getTime()) + fileName; File file = new File(path); if (!file.exists()) { file.mkdirs(); } file = new File(path + "/" + fileName); if (!file.exists()) { file.createNewFile(); } path = path + "/" + fileName; FileOutputStream fos = null; InputStream s = null; try { fos = new FileOutputStream(file); s = multipartFile.getInputStream(); byte[] buffer = new byte[1024]; int read = 0; while ((read = s.read(buffer)) != -1) { fos.write(buffer, 0, read); } fos.flush(); } catch (Exception e) { e.printStackTrace(); } finally { if (fos != null) { fos.close(); } if (s != null) { s.close(); } } */ if (StringUtils.isNotEmpty(path)) { // ???? SessionUser sessionUser = (SessionUser) request.getSession().getAttribute(CONFIG.SESSION_USER); String userId = sessionUser.getUser_id(); String userName = sessionUser.getUser_name(); Date nowDate = new Date(); // ? picture.setPicture_id(new GUID().toString()); picture.setCreate_time(nowDate); picture.setUser_id(userId); picture.setUser_name(userName); path = path.replaceAll("\\\\", "/"); picture.setPath(path); // dao.insertPicture(picture); // ???? ajaxResponse.setSuccess(true); ajaxResponse.setSuccessMessage("??"); //? Map map = new HashMap(); map.put("URL", basePath + "picture"); ajaxResponse.setExtParam(map); } else { // ???? ajaxResponse.setError(true); ajaxResponse.setErrorMessage("?"); } // ? LogUtils.updateOperationLog(request, OperationType.INSERT, "?" + picture.getPicture_id()); response.setContentType("text/html;charset=utf-8"); JSONObject obj = JSONObject.fromObject(ajaxResponse); response.getWriter().write(obj.toString()); return; }
From source file:org.openmrs.module.clinicalsummary.web.controller.utils.ExtendedDataGeneralController.java
@RequestMapping(method = RequestMethod.POST) public void processRequest(final @RequestParam(required = true, value = "data") MultipartFile data, final @RequestParam(required = true, value = "conceptNames") String conceptNames, final HttpServletResponse response) throws IOException { List<Concept> concepts = new ArrayList<Concept>(); for (String conceptName : StringUtils.splitPreserveAllTokens(conceptNames, ",")) { Concept concept = Context.getConceptService().getConcept(conceptName); if (concept != null) concepts.add(concept);//from w w w . j a v a 2s . c om } PatientService patientService = Context.getPatientService(); PatientSetService patientSetService = Context.getPatientSetService(); File identifierData = File.createTempFile(STUDY_DATA, INPUT_PREFIX); OutputStream identifierDataStream = new BufferedOutputStream(new FileOutputStream(identifierData)); FileCopyUtils.copy(data.getInputStream(), identifierDataStream); File extendedData = File.createTempFile(STUDY_DATA, OUTPUT_PREFIX); BufferedWriter writer = new BufferedWriter(new FileWriter(extendedData)); String line; BufferedReader reader = new BufferedReader(new FileReader(identifierData)); while ((line = reader.readLine()) != null) { Patient patient = null; if (isDigit(StringUtils.trim(line))) patient = patientService.getPatient(NumberUtils.toInt(line)); else { Cohort cohort = patientSetService.convertPatientIdentifier(Arrays.asList(line)); for (Integer patientId : cohort.getMemberIds()) { Patient cohortPatient = patientService.getPatient(patientId); if (cohortPatient != null && !cohortPatient.isVoided()) patient = cohortPatient; } } if (patient != null) { ExtendedData extended = new ExtendedData(patient, null); extended.setEncounters(searchEncounters(patient)); for (Concept concept : concepts) extended.addObservations(concept, searchObservations(patient, concept)); writer.write(extended.generatePatientData()); writer.newLine(); ResultCacheInstance.getInstance().clearCache(patient); } else { writer.write("Unresolved patient id or patient identifier for " + line); writer.newLine(); } } reader.close(); writer.close(); InputStream inputStream = new BufferedInputStream(new FileInputStream(extendedData)); response.setHeader("Content-Disposition", "attachment; filename=" + data.getName()); response.setContentType("text/plain"); FileCopyUtils.copy(inputStream, response.getOutputStream()); }
From source file:org.openmrs.module.clinicalsummary.web.controller.utils.ExtendedDataEncounterController.java
@RequestMapping(method = RequestMethod.POST) public void processSubmit(final @RequestParam(required = true, value = "data") MultipartFile data, final @RequestParam(required = true, value = "conceptNames") String conceptNames, final HttpServletResponse response) throws IOException { List<Concept> concepts = new ArrayList<Concept>(); for (String conceptName : StringUtils.splitPreserveAllTokens(conceptNames, ",")) { Concept concept = Context.getConceptService().getConcept(conceptName); if (concept != null) concepts.add(concept);//from w w w . j av a 2s . c o m } PatientService patientService = Context.getPatientService(); PatientSetService patientSetService = Context.getPatientSetService(); File identifierData = File.createTempFile(STUDY_DATA, INPUT_PREFIX); OutputStream identifierDataStream = new BufferedOutputStream(new FileOutputStream(identifierData)); FileCopyUtils.copy(data.getInputStream(), identifierDataStream); File extendedData = File.createTempFile(STUDY_DATA, OUTPUT_PREFIX); BufferedWriter writer = new BufferedWriter(new FileWriter(extendedData)); String line; BufferedReader reader = new BufferedReader(new FileReader(identifierData)); while ((line = reader.readLine()) != null) { Patient patient = null; String[] elements = StringUtils.splitPreserveAllTokens(line, ","); try { if (isDigit(StringUtils.trim(elements[1]))) patient = patientService.getPatient(NumberUtils.toInt(elements[1])); else { Cohort cohort = patientSetService.convertPatientIdentifier(Arrays.asList(elements[1])); for (Integer patientId : cohort.getMemberIds()) { Patient cohortPatient = patientService.getPatient(patientId); if (cohortPatient != null && !cohortPatient.isVoided()) patient = cohortPatient; } } } catch (Exception e) { log.error("Unable to resolve patients!", e); } Date referenceDate = WebUtils.parse(elements[2], "MM/dd/yyyy", new Date()); if (patient != null) { ExtendedData extended = new ExtendedData(patient, referenceDate); extended.setEncounters(searchEncounters(patient)); for (Concept concept : concepts) extended.addObservations(concept, searchObservations(patient, concept)); writer.write(extended.generateEncounterData()); writer.newLine(); ResultCacheInstance.getInstance().clearCache(patient); } else { writer.write("Unresolved patient id or patient identifier for " + elements[1]); writer.newLine(); } } reader.close(); writer.close(); InputStream inputStream = new BufferedInputStream(new FileInputStream(extendedData)); response.setHeader("Content-Disposition", "attachment; filename=generated-" + data.getOriginalFilename()); response.setContentType("text/plain"); FileCopyUtils.copy(inputStream, response.getOutputStream()); }
From source file:org.kievguide.controller.UserController.java
@RequestMapping(value = "/settingssave", method = RequestMethod.POST) public ModelAndView settingsSave(@CookieValue(value = "userstatus", defaultValue = "guest") String useremail, @RequestParam("firstname") String firstname, @RequestParam("lastname") String lastname, @RequestParam("email") String email, @RequestParam("password") String password, @RequestParam("photosrc") MultipartFile file, HttpServletResponse response, HttpServletRequest request) throws FileNotFoundException, IOException { ModelAndView modelAndView = new ModelAndView(); SecureRandom random = new SecureRandom(); String photoname = new BigInteger(130, random).toString(32); Place place = new Place(); User user = userService.searchUser(useremail); user.setFirstname(firstname);/*from w ww.j av a 2 s . co m*/ user.setLastname(lastname); user.setPassword(password); user.setEmail(email); if (!file.isEmpty()) { String folder = request.getSession().getServletContext().getRealPath(""); folder = folder.substring(0, 30); BufferedOutputStream stream = new BufferedOutputStream( new FileOutputStream(new File(folder + "/src/main/webapp/img/" + photoname + ".jpg"))); FileCopyUtils.copy(file.getInputStream(), stream); stream.close(); user.setPhotosrc("img/" + photoname + ".jpg"); } userService.addUser(user); Cookie userCookie = new Cookie("userstatus", user.getEmail()); response.addCookie(userCookie); String userStatus = Util.userPanel(user.getEmail()); modelAndView.addObject("userstatus", userStatus); return new ModelAndView("redirect:" + "firstrequest"); }
From source file:com.dlshouwen.jspc.zwpc.controller.SelfEvaluateController.java
private String uploadFile(HttpServletRequest request, String fname) throws IOException { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; MultipartFile multipartFile = multipartRequest.getFile(fname); String fileName = multipartFile.getOriginalFilename(); String filePath = ""; if (null != multipartFile && StringUtils.isNotEmpty(multipartFile.getOriginalFilename())) { JSONObject jobj = FileUploadClient.upFile(request, fileName, multipartFile.getInputStream()); if (jobj.getString("responseMessage").equals("OK")) { filePath = jobj.getString("fpath"); }//www. j a va2 s.co m } /* if (fileName.trim().length() > 0) { int pos = fileName.lastIndexOf("."); fileName = fileName.substring(pos); String fileDirPath = request.getSession().getServletContext().getRealPath("/"); String path = fileDirPath.substring(0, fileDirPath.lastIndexOf(File.separator)) + CONFIG.UPLOAD_FILE_PATH; Date date = new Date(); fileName = String.valueOf(date.getTime()) + fileName; File file = new File(path); if (!file.exists()) { file.mkdirs(); } file = new File(path + "/" + fileName); if (!file.exists()) { try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } path = path + "/" + fileName; FileOutputStream fos = null; InputStream s = null; try { fos = new FileOutputStream(file); s = multipartFile.getInputStream(); byte[] buffer = new byte[1024]; int read = 0; while ((read = s.read(buffer)) != -1) { fos.write(buffer, 0, read); } fos.flush(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (fos != null) { fos.close(); } if (s != null) { s.close(); } } catch (Exception e) { e.printStackTrace(); } } path = path.replaceAll("\\\\", "/"); filePath = path; } */ return filePath; }