List of usage examples for org.springframework.web.multipart MultipartFile getBytes
byte[] getBytes() throws IOException;
From source file:org.openmrs.module.feedback.web.AddFeedbackFormController.java
@Override protected Boolean formBackingObject(HttpServletRequest request) throws Exception { /* To check wheather or not the subject , severity and feedback is empty or not */ Boolean feedbackMessage = false; String text = ""; String subject = request.getParameter("subject"); String severity = request.getParameter("severity"); String feedback = request.getParameter("feedback"); if (StringUtils.hasLength(subject) && StringUtils.hasLength(severity) && StringUtils.hasLength(severity)) { Object o = Context.getService(FeedbackService.class); FeedbackService service = (FeedbackService) o; Feedback s = new Feedback(); s.setSubject(request.getParameter("subject")); s.setSeverity(request.getParameter("severity")); /* To get the Stacktrace of the page from which the feedback is submitted */ StackTraceElement[] c = Thread.currentThread().getStackTrace(); if ("Yes".equals(request.getParameter("pagecontext"))) { for (int i = 0; i < c.length; i++) { feedback = feedback + System.getProperty("line.separator") + c[i].getFileName() + c[i].getMethodName() + c[i].getClass() + c[i].getLineNumber(); }//from w w w .ja v a 2 s . co m } s.setContent(feedback); /* file upload in multiplerequest */ if (request instanceof MultipartHttpServletRequest) { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; MultipartFile file = (MultipartFile) multipartRequest.getFile("file"); if (!file.isEmpty()) { if (file.getSize() <= 5242880) { if (file.getOriginalFilename().endsWith(".jpeg") || file.getOriginalFilename().endsWith(".jpg") || file.getOriginalFilename().endsWith(".gif") || file.getOriginalFilename().endsWith(".png")) { s.setMessage(file.getBytes()); } else { request.getSession().setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "feedback.notification.feedback.error"); return false; } } else { request.getSession().setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "feedback.notification.feedback.error"); return false; } } } /* Save the Feedback */ service.saveFeedback(s); request.getSession().setAttribute(WebConstants.OPENMRS_MSG_ATTR, Context.getAdministrationService().getGlobalProperty("feedback.ui.notification")); if ("Yes".equals(Context.getUserContext().getAuthenticatedUser() .getUserProperty("feedback_notificationReceipt"))) { try { // Create Message Message message = new Message(); message.setSender( Context.getAdministrationService().getGlobalProperty("feedback.notification.email")); message.setRecipients( Context.getUserContext().getAuthenticatedUser().getUserProperty("feedback_email")); message.setSubject("Feedback submission confirmation mail"); message.setContent(Context.getAdministrationService().getGlobalProperty("feedback.notification") + "Ticket Number: " + s.getFeedbackId() + " Subject :" + s.getSubject()); message.setSentDate(new Date()); // Send message Context.getMessageService().send(message); } catch (Exception e) { log.error("Unable to sent the email to the Email : " + Context.getUserContext().getAuthenticatedUser().getUserProperty("feedback_email")); } } try { // Create Message Message message = new Message(); message.setSender( Context.getAdministrationService().getGlobalProperty("feedback.notification.email")); message.setRecipients( Context.getAdministrationService().getGlobalProperty("feedback.admin.notification.email")); message.setSubject("New feedback submitted"); message.setContent( Context.getAdministrationService().getGlobalProperty("feedback.admin.notification") + "Ticket Number: " + s.getFeedbackId() + " Subject : " + s.getSubject() + " Take Action :" + request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/module/feedback/feedback.form?feedbackId=" + s.getFeedbackId() + "#command"); message.setSentDate(new Date()); // Send message Context.getMessageService().send(message); } catch (Exception e) { log.error("Unable to sent the email to the Email : " + Context.getUserContext() .getAuthenticatedUser().getUserProperty("feedback.admin.notification.email")); } feedbackMessage = true; } /* Reserved for future use for showing that the data is saved and the feedback is submitted */ log.debug("Returning hello world text: " + text); return feedbackMessage; }
From source file:ua.aits.sdolyna.controller.SystemController.java
@RequestMapping(value = { "/Sdolyna/system/do/uploadimage", "/system/do/uploadimage", "/Sdolyna/system/do/uploadimage/", "/system/do/uploadimage/" }, method = RequestMethod.POST) public @ResponseBody String uploadImageHandler(@RequestParam("file") MultipartFile file, @RequestParam("path") String path, HttpServletRequest request) { Integer curent = Integer.parseInt(Helpers.lastFileModified(Constants.home + path).getName().split("\\.")[0]) + 1;/*from www. j a va2 s. co m*/ String ext = file.getOriginalFilename().split("\\.")[1]; String name = curent.toString() + "." + ext; if (!file.isEmpty()) { try { byte[] bytes = file.getBytes(); File dir = new File(Constants.home + path); if (!dir.exists()) dir.mkdirs(); File serverFile = new File(dir.getAbsolutePath() + File.separator + name); try (BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile))) { stream.write(bytes); } return name; } catch (Exception e) { return "You failed to upload " + name + " => " + e.getMessage(); } } else { return "You failed to upload " + name + " because the file was empty."; } }
From source file:ua.aits.sdolyna.controller.SystemController.java
@RequestMapping(value = { "/Sdolyna/system/do/uploadfile", "/system/do/uploadfile", "/Sdolyna/system/do/uploadfile/", "/system/do/uploadfile/" }, method = RequestMethod.POST) public @ResponseBody String uploadFileHandler(@RequestParam("file") MultipartFile file, @RequestParam("path") String path, HttpServletRequest request) { Integer curent = Integer.parseInt(Helpers.lastFileModified(Constants.home + path).getName().split("\\.")[0]) + 1;/*from w w w.j av a 2 s .co m*/ String ext = file.getOriginalFilename().split("\\.")[1]; String name = curent.toString() + "." + ext; if (!file.isEmpty()) { try { byte[] bytes = file.getBytes(); File dir = new File(Constants.home + path); if (!dir.exists()) dir.mkdirs(); File serverFile = new File(dir.getAbsolutePath() + File.separator + name); try (BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile))) { stream.write(bytes); } return name; } catch (Exception e) { return "You failed to upload " + name + " => " + e.getMessage(); } } else { return "You failed to upload " + name + " because the file was empty."; } }
From source file:cz.zcu.kiv.eegdatabase.logic.controller.experiment.AddDataFileController.java
/** * Processing of the valid form//from www .j av a 2 s.c om */ @Override protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException bindException) throws Exception { log.debug("Processing form data."); AddDataFileCommand addDataCommand = (AddDataFileCommand) command; MultipartHttpServletRequest mpRequest = (MultipartHttpServletRequest) request; // the map containing file names mapped to files Map m = mpRequest.getFileMap(); Set set = m.keySet(); for (Object key : set) { MultipartFile file = (MultipartFile) m.get(key); if (file == null) { log.error("No file was uploaded!"); } else { log.debug("Creating measuration with ID " + addDataCommand.getMeasurationId()); Experiment experiment = new Experiment(); experiment.setExperimentId(addDataCommand.getMeasurationId()); if (file.getOriginalFilename().endsWith(".zip")) { ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(file.getBytes())); ZipEntry en = zis.getNextEntry(); while (en != null) { if (en.isDirectory()) { en = zis.getNextEntry(); continue; } DataFile data = new DataFile(); data.setExperiment(experiment); String name[] = en.getName().split("/"); data.setFilename(name[name.length - 1]); data.setDescription(addDataCommand.getDescription()); data.setFileContent(Hibernate.createBlob(zis)); String[] partOfName = en.getName().split("[.]"); data.setMimetype(partOfName[partOfName.length - 1]); dataFileDao.create(data); en = zis.getNextEntry(); } } else { log.debug("Creating new Data object."); DataFile data = new DataFile(); data.setExperiment(experiment); log.debug("Original name of uploaded file: " + file.getOriginalFilename()); String filename = file.getOriginalFilename().replace(" ", "_"); data.setFilename(filename); log.debug("MIME type of the uploaded file: " + file.getContentType()); if (file.getContentType().length() > MAX_MIMETYPE_LENGTH) { int index = filename.lastIndexOf("."); data.setMimetype(filename.substring(index)); } else { data.setMimetype(file.getContentType()); } log.debug("Parsing the sapmling rate."); data.setDescription(addDataCommand.getDescription()); log.debug("Setting the binary data to object."); data.setFileContent(Hibernate.createBlob(file.getBytes())); dataFileDao.create(data); log.debug("Data stored into database."); } } } log.debug("Returning MAV"); ModelAndView mav = new ModelAndView( "redirect:/experiments/detail.html?experimentId=" + addDataCommand.getMeasurationId()); return mav; }
From source file:com.web.mavenproject6.controller.UserController.java
@ResponseBody @RequestMapping(value = "/profile/upload", method = RequestMethod.POST) public String handleUpload(@RequestParam(value = "uploadfile", required = false) MultipartFile uploadfile, @RequestParam(value = "propId") String propId, HttpServletResponse httpServletResponse) throws IOException { Object pObject = personalService.findByAccessNumber(propId); if (pObject instanceof personal) { personal person = (personal) pObject; person.setLastUpdate(new Date()); person.setPhoto(uploadfile.getBytes()); personalService.getRepository().save(person); return "success"; }/*from w w w. jav a2 s . c om*/ Object gObject = guestService.findByAccessNumber(propId); if (gObject instanceof guest) { guest g = (guest) gObject; g.getPersonal_guest().setLastUpdate(new Date()); g.setPhoto(uploadfile.getBytes()); guestService.getRepository().save(g); return "success"; } return "failed"; }
From source file:ua.aits.sdolyna.controller.SystemController.java
@RequestMapping(value = { "/Sdolyna/uploadFile", "/uploadFile", "/Sdolyna/uploadFile/", "/uploadFile/" }, method = RequestMethod.POST) public @ResponseBody String uploadFileHandlerFull(@RequestParam("upload") MultipartFile file, @RequestParam("path") String path, HttpServletRequest request) { Integer curent = Integer.parseInt(Helpers.lastFileModified(Constants.home + path).getName().split("\\.")[0]) + 1;/*from w w w . j a va 2 s . c om*/ String ext = file.getOriginalFilename().split("\\.")[1]; String name = curent.toString() + "." + ext; if (!file.isEmpty()) { try { byte[] bytes = file.getBytes(); // Creating the directory to store file File dir = new File(Constants.home + path); if (!dir.exists()) dir.mkdirs(); // Create the file on server File serverFile = new File(dir.getAbsolutePath() + File.separator + name); try (BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile))) { stream.write(bytes); } String link_path = serverFile.getAbsolutePath().replace(Constants.home, ""); return "<img class=\"main-img\" src=\"" + Constants.URL + link_path + "\" realpath='" + link_path + "' alt='" + link_path + file.getName() + "' />"; } catch (Exception e) { return "You failed to upload " + name + " => " + e.getMessage(); } } else { return "You failed to upload " + name + " because the file was empty."; } }
From source file:com.glaf.template.web.springmvc.MxSystemTemplateController.java
@RequestMapping("/save") public ModelAndView save(HttpServletRequest request, ModelMap modelMap) throws IOException { LoginContext loginContext = RequestUtils.getLoginContext(request); String templateId = request.getParameter("templateId"); Template template = null;/*from w w w.java 2s. c o m*/ if (StringUtils.isNotEmpty(templateId)) { template = templateService.getTemplate(templateId); } if (template == null) { template = new Template(); template.setCreateBy(loginContext.getActorId()); } MultipartHttpServletRequest req = (MultipartHttpServletRequest) request; Map<String, Object> paramMap = RequestUtils.getParameterMap(req); Tools.populate(template, paramMap); String nodeId = ParamUtils.getString(paramMap, "nodeId"); if (nodeId != null) { } Map<String, MultipartFile> fileMap = req.getFileMap(); Set<Entry<String, MultipartFile>> entrySet = fileMap.entrySet(); for (Entry<String, MultipartFile> entry : entrySet) { MultipartFile mFile = entry.getValue(); String filename = mFile.getOriginalFilename(); if (mFile.getSize() > 0) { template.setFileSize(mFile.getSize()); int fileType = 0; if (filename.endsWith(".java")) { fileType = 50; template.setContent(new String(mFile.getBytes())); } else if (filename.endsWith(".jsp")) { fileType = 51; template.setContent(new String(mFile.getBytes())); } else if (filename.endsWith(".ftl")) { fileType = 52; template.setLanguage("freemarker"); template.setContent(new String(mFile.getBytes())); } else if (filename.endsWith(".vm")) { fileType = 54; template.setLanguage("velocity"); template.setContent(new String(mFile.getBytes())); } else if (filename.endsWith(".xml")) { fileType = 60; template.setContent(new String(mFile.getBytes())); } else if (filename.endsWith(".htm") || filename.endsWith(".html")) { fileType = 80; template.setContent(new String(mFile.getBytes())); } else if (filename.endsWith(".js")) { fileType = 82; template.setContent(new String(mFile.getBytes())); } else if (filename.endsWith(".css")) { fileType = 84; template.setContent(new String(mFile.getBytes())); } else if (filename.endsWith(".txt")) { fileType = 85; template.setContent(new String(mFile.getBytes())); } template.setDataFile(filename); template.setFileType(fileType); template.setCreateDate(new Date()); template.setData(mFile.getBytes()); template.setLastModified(System.currentTimeMillis()); template.setTemplateType(FileUtils.getFileExt(filename)); break; } } templateService.saveTemplate(template); return this.list(request, modelMap); }
From source file:org.literacyapp.web.content.multimedia.image.ImageEditController.java
@RequestMapping(value = "/{id}", method = RequestMethod.POST) public String handleSubmit(HttpSession session, Image image, @RequestParam("bytes") MultipartFile multipartFile, BindingResult result, Model model) { logger.info("handleSubmit"); if (StringUtils.isBlank(image.getTitle())) { result.rejectValue("title", "NotNull"); } else {/*from www.j a v a2 s . c o m*/ Image existingImage = imageDao.read(image.getTitle(), image.getLocale()); if ((existingImage != null) && !existingImage.getId().equals(image.getId())) { result.rejectValue("title", "NonUnique"); } } try { byte[] bytes = multipartFile.getBytes(); if (multipartFile.isEmpty() || (bytes == null) || (bytes.length == 0)) { result.rejectValue("bytes", "NotNull"); } else { String originalFileName = multipartFile.getOriginalFilename(); logger.info("originalFileName: " + originalFileName); if (originalFileName.toLowerCase().endsWith(".png")) { image.setImageFormat(ImageFormat.PNG); } else if (originalFileName.toLowerCase().endsWith(".jpg") || originalFileName.toLowerCase().endsWith(".jpeg")) { image.setImageFormat(ImageFormat.JPG); } else if (originalFileName.toLowerCase().endsWith(".gif")) { image.setImageFormat(ImageFormat.GIF); } else { result.rejectValue("bytes", "typeMismatch"); } if (image.getImageFormat() != null) { String contentType = multipartFile.getContentType(); logger.info("contentType: " + contentType); image.setContentType(contentType); image.setBytes(bytes); if (image.getImageFormat() != ImageFormat.GIF) { int width = ImageHelper.getWidth(bytes); logger.info("width: " + width + "px"); if (width < ImageHelper.MINIMUM_WIDTH) { result.rejectValue("bytes", "image.too.small"); image.setBytes(null); } else { if (width > ImageHelper.MINIMUM_WIDTH) { bytes = ImageHelper.scaleImage(bytes, ImageHelper.MINIMUM_WIDTH); image.setBytes(bytes); } } } } } } catch (IOException e) { logger.error(e); } if (result.hasErrors()) { model.addAttribute("image", image); model.addAttribute("contentLicenses", ContentLicense.values()); model.addAttribute("literacySkills", LiteracySkill.values()); model.addAttribute("numeracySkills", NumeracySkill.values()); model.addAttribute("contentCreationEvents", contentCreationEventDao.readAll(image)); return "content/multimedia/image/edit"; } else { image.setTitle(image.getTitle().toLowerCase()); image.setTimeLastUpdate(Calendar.getInstance()); image.setRevisionNumber(Integer.MIN_VALUE); imageDao.update(image); Contributor contributor = (Contributor) session.getAttribute("contributor"); ContentCreationEvent contentCreationEvent = new ContentCreationEvent(); contentCreationEvent.setContributor(contributor); contentCreationEvent.setContent(image); contentCreationEvent.setCalendar(Calendar.getInstance()); contentCreationEventDao.update(contentCreationEvent); if (EnvironmentContextLoaderListener.env == Environment.PROD) { String text = URLEncoder .encode(contributor.getFirstName() + " just edited an Image:\n" + " Language: " + image.getLocale().getLanguage() + "\n" + " Title: \"" + image.getTitle() + "\"\n" + " Image format: " + image.getImageFormat() + "\n" + "See ") + "http://literacyapp.org/content/multimedia/image/list"; String iconUrl = contributor.getImageUrl(); SlackApiHelper.postMessage(Team.CONTENT_CREATION, text, iconUrl, "http://literacyapp.org/image/" + image.getId() + "." + image.getImageFormat().toString().toLowerCase()); } return "redirect:/content/multimedia/image/list"; } }
From source file:org.iti.agrimarket.view.UserController.java
@RequestMapping(value = { "/uprofile.htm" }, method = RequestMethod.POST) public String updateUserProfile(@RequestParam(value = "fullName", required = true) String fullName, @RequestParam(value = "mobile", required = true) String mobil, @RequestParam(value = "governerate", required = true) String governerate, @RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, Locale locale, Model model) { System.out.println("hhhhhhhhhhhhhhhhhhhhhh" + file.getName()); String language = locale.getLanguage(); locale = LocaleContextHolder.getLocale(); User user = (User) request.getSession().getAttribute("user"); if (user != null) { user.setFullName(fullName);// w w w . ja va2 s .c o m user.setGovernerate(governerate); if (file != null) { try { user.setImage(file.getBytes()); byte[] image = user.getImage(); MagicMatch match = null; try { match = Magic.getMagicMatch(image); } catch (MagicParseException ex) { Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex); } catch (MagicMatchNotFoundException ex) { Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex); } catch (MagicException ex) { Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex); } String ext = null; if (match != null) ext = "." + match.getExtension(); File parentDir = new File(Constants.IMAGE_PATH + Constants.USER_PATH); if (!parentDir.isDirectory()) { parentDir.mkdirs(); } BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream( new File(Constants.IMAGE_PATH + Constants.USER_PATH + file.getOriginalFilename()))); stream.write(image); stream.close(); user.setImageUrl( Constants.IMAGE_PRE_URL + Constants.USER_PATH + file.getOriginalFilename() + ext); } catch (IOException ex) { Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex); } } user.setMobile(mobil); int res = userService.updateUser(user); if (res != 0) { request.getSession().setAttribute("user", user); } model.addAttribute("user", user); } model.addAttribute("lang", locale); return "profile"; }
From source file:org.literacyapp.web.content.multimedia.audio.AudioEditController.java
@RequestMapping(value = "/{id}", method = RequestMethod.POST) public String handleSubmit(HttpSession session, Audio audio, @RequestParam("bytes") MultipartFile multipartFile, BindingResult result, Model model) { logger.info("handleSubmit"); if (StringUtils.isBlank(audio.getTranscription())) { result.rejectValue("transcription", "NotNull"); } else {/*from w w w .j ava 2s.c o m*/ Audio existingAudio = audioDao.read(audio.getTranscription(), audio.getLocale()); if ((existingAudio != null) && !existingAudio.getId().equals(audio.getId())) { result.rejectValue("transcription", "NonUnique"); } } try { byte[] bytes = multipartFile.getBytes(); if (multipartFile.isEmpty() || (bytes == null) || (bytes.length == 0)) { result.rejectValue("bytes", "NotNull"); } else { String originalFileName = multipartFile.getOriginalFilename(); logger.info("originalFileName: " + originalFileName); if (originalFileName.toLowerCase().endsWith(".mp3")) { audio.setAudioFormat(AudioFormat.MP3); } else if (originalFileName.toLowerCase().endsWith(".ogg")) { audio.setAudioFormat(AudioFormat.OGG); } else if (originalFileName.toLowerCase().endsWith(".wav")) { audio.setAudioFormat(AudioFormat.WAV); } else { result.rejectValue("bytes", "typeMismatch"); } if (audio.getAudioFormat() != null) { String contentType = multipartFile.getContentType(); logger.info("contentType: " + contentType); audio.setContentType(contentType); audio.setBytes(bytes); // TODO: convert to a default audio format? } } } catch (IOException e) { logger.error(e); } if (result.hasErrors()) { model.addAttribute("audio", audio); model.addAttribute("contentLicenses", ContentLicense.values()); model.addAttribute("literacySkills", LiteracySkill.values()); model.addAttribute("numeracySkills", NumeracySkill.values()); model.addAttribute("contentCreationEvents", contentCreationEventDao.readAll(audio)); return "content/multimedia/audio/edit"; } else { audio.setTranscription(audio.getTranscription().toLowerCase()); audio.setTimeLastUpdate(Calendar.getInstance()); audio.setRevisionNumber(Integer.MIN_VALUE); audioDao.update(audio); Contributor contributor = (Contributor) session.getAttribute("contributor"); ContentCreationEvent contentCreationEvent = new ContentCreationEvent(); contentCreationEvent.setContributor(contributor); contentCreationEvent.setContent(audio); contentCreationEvent.setCalendar(Calendar.getInstance()); contentCreationEventDao.update(contentCreationEvent); if (EnvironmentContextLoaderListener.env == Environment.PROD) { String text = URLEncoder.encode(contributor.getFirstName() + " just edited an Audio:\n" + " Language: " + audio.getLocale().getLanguage() + "\n" + " Transcription: \"" + audio.getTranscription() + "\"\n" + " Audio format: " + audio.getAudioFormat() + "\n" + "See ") + "http://literacyapp.org/content/multimedia/audio/list"; String iconUrl = contributor.getImageUrl(); SlackApiHelper.postMessage(Team.CONTENT_CREATION, text, iconUrl, "http://literacyapp.org/audio/" + audio.getId() + "." + audio.getAudioFormat().toString().toLowerCase()); } return "redirect:/content/multimedia/audio/list"; } }