List of usage examples for org.springframework.web.multipart MultipartFile isEmpty
boolean isEmpty();
From source file:org.literacyapp.web.content.multimedia.image.ImageCreateController.java
@RequestMapping(method = RequestMethod.POST) public String handleSubmit(HttpSession session, /*@Valid*/ Image image, @RequestParam("bytes") MultipartFile multipartFile, BindingResult result, Model model) { logger.info("handleSubmit"); if (StringUtils.isBlank(image.getTitle())) { result.rejectValue("title", "NotNull"); } else {/*ww w .ja va 2s . c o m*/ Image existingImage = imageDao.read(image.getTitle(), image.getLocale()); if (existingImage != null) { 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("contentLicenses", ContentLicense.values()); model.addAttribute("literacySkills", LiteracySkill.values()); model.addAttribute("numeracySkills", NumeracySkill.values()); return "content/multimedia/image/create"; } else { image.setTitle(image.getTitle().toLowerCase()); int[] dominantColor = ImageColorHelper.getDominantColor(image.getBytes()); image.setDominantColor( "rgb(" + dominantColor[0] + "," + dominantColor[1] + "," + dominantColor[2] + ")"); image.setTimeLastUpdate(Calendar.getInstance()); imageDao.create(image); Contributor contributor = (Contributor) session.getAttribute("contributor"); ContentCreationEvent contentCreationEvent = new ContentCreationEvent(); contentCreationEvent.setContributor(contributor); contentCreationEvent.setContent(image); contentCreationEvent.setCalendar(Calendar.getInstance()); contentCreationEventDao.create(contentCreationEvent); if (EnvironmentContextLoaderListener.env == Environment.PROD) { String text = URLEncoder .encode(contributor.getFirstName() + " just added a new 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:de.hska.ld.core.controller.UserController.java
@Secured(Core.ROLE_USER) @RequestMapping(method = RequestMethod.POST, value = "/avatar") public Callable uploadAvatar(@RequestParam MultipartFile file) { return () -> { String name = file.getOriginalFilename(); if (!file.isEmpty()) { userService.uploadAvatar(file, name); return new ResponseEntity<>(HttpStatus.OK); } else {/*w w w . j a v a 2s .c om*/ throw new ValidationException("file"); } }; }
From source file:csns.web.controller.AssignmentControllerS.java
@RequestMapping(value = "/assignment/edit", method = RequestMethod.POST) public String edit(@ModelAttribute Assignment assignment, @RequestParam(value = "file", required = false) MultipartFile uploadedFile, HttpServletRequest request, BindingResult result, SessionStatus sessionStatus) { assignmentValidator.validate(assignment, uploadedFile, result); if (result.hasErrors()) return assignment.isOnline() ? "assignment/online/edit" : "assignment/edit"; if (!assignment.isOnline()) { Resource description = assignment.getDescription(); if (description.getType() == ResourceType.NONE) assignment.setDescription(null); else if (description.getType() == ResourceType.FILE && uploadedFile != null && !uploadedFile.isEmpty()) description.setFile(fileIO.save(uploadedFile, SecurityUtils.getUser(), false)); }/* w w w .j av a 2 s.c om*/ assignment = assignmentDao.saveAssignment(assignment); sessionStatus.setComplete(); logger.info(SecurityUtils.getUser().getUsername() + " edited assignment " + assignment.getId()); return assignment.isOnline() && request.getParameter("next") != null ? "redirect:/assignment/online/editQuestionSheet?assignmentId=" + assignment.getId() : "redirect:/section/taught#section-" + assignment.getSection().getId(); }
From source file:de.document.service.MedikamentService.java
public String transferToFile(MultipartFile file) throws Throwable { String filePath2 = Thread.currentThread().getContextClassLoader().getResource("medikament") + "\\" + file.getOriginalFilename(); String filePath = filePath2.substring(6); if (!file.isEmpty()) { try {/*from w ww. j av a 2 s. c om*/ byte[] bytes = file.getBytes(); BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(filePath))); stream.write(bytes); stream.close(); return filePath; } catch (Exception e) { System.out.println("You failed to upload " + file.getOriginalFilename() + " => " + e.getMessage()); } } else { System.out .println("You failed to upload " + file.getOriginalFilename() + " because the file was empty."); } return null; }
From source file:com.mbv.web.rest.controller.VpGrnController.java
/** * @??excel//from ww w . java 2s . com * @2015916 * @param * @version */ @RequestMapping(value = "/importGrn", method = RequestMethod.POST) @ResponseBody public void importBill(@RequestParam(value = "add_vpGrn_importedFile", required = false) MultipartFile file, HttpServletRequest request, HttpServletResponse response) { JSONObject json = new JSONObject(); try { // ? if (file.isEmpty()) { throw new MbvException("??"); } // ?? if (file.getSize() > 20971520) { throw new Exception("?20M?"); } json = importFile(file); } catch (MbvException me) { me.printStackTrace(); json.put("success", false); json.put("msg", me.getMessage()); } catch (RuntimeException re) { re.printStackTrace(); json.put("success", false); json.put("msg", re.getMessage()); } catch (Exception e) { e.printStackTrace(); json.put("success", false); json.put("msg", e.getMessage()); } // ??? outPrintJson(response, json.toString()); }
From source file:org.literacyapp.web.content.multimedia.video.VideoEditController.java
@RequestMapping(value = "/{id}", method = RequestMethod.POST) public String handleSubmit(HttpSession session, Video video, @RequestParam("bytes") MultipartFile multipartFile, BindingResult result, Model model) { logger.info("handleSubmit"); if (StringUtils.isBlank(video.getTitle())) { result.rejectValue("title", "NotNull"); } else {//from w ww . jav a 2 s .c om Video existingVideo = videoDao.read(video.getTitle(), video.getLocale()); if ((existingVideo != null) && !existingVideo.getId().equals(video.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(".m4v")) { video.setVideoFormat(VideoFormat.M4V); } else if (originalFileName.toLowerCase().endsWith(".mp4")) { video.setVideoFormat(VideoFormat.MP4); } else { result.rejectValue("bytes", "typeMismatch"); } if (video.getVideoFormat() != null) { String contentType = multipartFile.getContentType(); logger.info("contentType: " + contentType); video.setContentType(contentType); video.setBytes(bytes); // TODO: convert to a default video format? } } } catch (IOException e) { logger.error(e); } if (result.hasErrors()) { model.addAttribute("video", video); model.addAttribute("contentLicenses", ContentLicense.values()); model.addAttribute("literacySkills", LiteracySkill.values()); model.addAttribute("numeracySkills", NumeracySkill.values()); model.addAttribute("contentCreationEvents", contentCreationEventDao.readAll(video)); return "content/multimedia/video/edit"; } else { video.setTitle(video.getTitle().toLowerCase()); video.setTimeLastUpdate(Calendar.getInstance()); video.setRevisionNumber(Integer.MIN_VALUE); videoDao.update(video); Contributor contributor = (Contributor) session.getAttribute("contributor"); ContentCreationEvent contentCreationEvent = new ContentCreationEvent(); contentCreationEvent.setContributor(contributor); contentCreationEvent.setContent(video); contentCreationEvent.setCalendar(Calendar.getInstance()); contentCreationEventDao.update(contentCreationEvent); if (EnvironmentContextLoaderListener.env == Environment.PROD) { String text = URLEncoder .encode(contributor.getFirstName() + " just edited an Video:\n" + " Language: \"" + video.getLocale().getLanguage() + "\n" + " Title: \"" + video.getTitle() + "\"\n" + " Video format: " + video.getVideoFormat() + "\n" + "See ") + "http://literacyapp.org/content/multimedia/video/list"; String iconUrl = contributor.getImageUrl(); SlackApiHelper.postMessage(Team.CONTENT_CREATION, text, iconUrl, "http://literacyapp.org/video/" + video.getId() + "." + video.getVideoFormat().toString().toLowerCase()); } return "redirect:/content/multimedia/video/list"; } }
From source file:com.mbv.web.rest.controller.VpGrnController.java
/** * @??excel//ww w . jav a 2 s . c om * @2015916 * @param * @version */ @RequestMapping(value = "/importUpdateGrn", method = RequestMethod.POST) @ResponseBody public void importUpdateBill( @RequestParam(value = "update_vpGrn_importedFile", required = false) MultipartFile file, HttpServletRequest request, HttpServletResponse response) { JSONObject json = new JSONObject(); try { // ? if (file.isEmpty()) { throw new MbvException("??"); } // ?? if (file.getSize() > 20971520) { throw new Exception("?20M?"); } json = importFile(file); } catch (MbvException me) { me.printStackTrace(); json.put("success", false); json.put("msg", me.getMessage()); } catch (RuntimeException re) { re.printStackTrace(); json.put("success", false); json.put("msg", re.getMessage()); } catch (Exception e) { e.printStackTrace(); json.put("success", false); json.put("msg", e.getMessage()); } // ??? outPrintJson(response, json.toString()); }
From source file:gov.guilin.controller.admin.SettingController.java
/** * //from ww w . j av a 2 s . co m */ @RequestMapping(value = "/update", method = RequestMethod.POST) public String update(Setting setting, MultipartFile watermarkImageFile, RedirectAttributes redirectAttributes) { if (!isValid(setting)) { return ERROR_VIEW; } if (setting.getUsernameMinLength() > setting.getUsernameMaxLength() || setting.getPasswordMinLength() > setting.getPasswordMinLength()) { return ERROR_VIEW; } Setting srcSetting = SettingUtils.get(); if (StringUtils.isEmpty(setting.getSmtpPassword())) { setting.setSmtpPassword(srcSetting.getSmtpPassword()); } if (watermarkImageFile != null && !watermarkImageFile.isEmpty()) { if (!fileService.isValid(FileType.image, watermarkImageFile)) { addFlashMessage(redirectAttributes, Message.error("admin.upload.invalid")); return "redirect:edit.jhtml"; } String watermarkImage = fileService.uploadLocal(FileType.image, watermarkImageFile); setting.setWatermarkImage(watermarkImage); } else { setting.setWatermarkImage(srcSetting.getWatermarkImage()); } setting.setCnzzSiteId(srcSetting.getCnzzSiteId()); setting.setCnzzPassword(srcSetting.getCnzzPassword()); SettingUtils.set(setting); cacheService.clear(); staticService.buildIndex(); staticService.buildOther(); OutputStream outputStream = null; try { org.springframework.core.io.Resource resource = new ClassPathResource(CommonAttributes.PROPERTIES_PATH); Properties properties = PropertiesLoaderUtils.loadProperties(resource); String templateUpdateDelay = properties.getProperty("template.update_delay"); String messageCacheSeconds = properties.getProperty("message.cache_seconds"); if (setting.getIsDevelopmentEnabled()) { if (!templateUpdateDelay.equals("0") || !messageCacheSeconds.equals("0")) { outputStream = new FileOutputStream(resource.getFile()); properties.setProperty("template.update_delay", "0"); properties.setProperty("message.cache_seconds", "0"); properties.store(outputStream, "PROPERTIES"); } } else { if (templateUpdateDelay.equals("0") || messageCacheSeconds.equals("0")) { outputStream = new FileOutputStream(resource.getFile()); properties.setProperty("template.update_delay", "3600"); properties.setProperty("message.cache_seconds", "3600"); properties.store(outputStream, "PROPERTIES"); } } } catch (Exception e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(outputStream); } addFlashMessage(redirectAttributes, SUCCESS_MESSAGE); return "redirect:edit.jhtml"; }
From source file:net.groupbuy.controller.admin.SettingController.java
/** * //from w ww .j a va2s . co m */ @RequestMapping(value = "/update", method = RequestMethod.POST) public String update(Setting setting, MultipartFile watermarkImageFile, RedirectAttributes redirectAttributes) { if (!isValid(setting)) { return ERROR_VIEW; } if (setting.getUsernameMinLength() > setting.getUsernameMaxLength() || setting.getPasswordMinLength() > setting.getPasswordMinLength()) { return ERROR_VIEW; } Setting srcSetting = SettingUtils.get(); if (StringUtils.isEmpty(setting.getSmtpPassword())) { setting.setSmtpPassword(srcSetting.getSmtpPassword()); } if (watermarkImageFile != null && !watermarkImageFile.isEmpty()) { if (!fileService.isValid(FileType.image, watermarkImageFile)) { addFlashMessage(redirectAttributes, Message.error("admin.upload.invalid")); return "redirect:edit.jhtml"; } String watermarkImage = fileService.uploadLocal(FileType.image, watermarkImageFile); setting.setWatermarkImage(watermarkImage); } else { setting.setWatermarkImage(srcSetting.getWatermarkImage()); } setting.setCnzzSiteId(srcSetting.getCnzzSiteId()); setting.setCnzzPassword(srcSetting.getCnzzPassword()); SettingUtils.set(setting); cacheService.clear(); staticService.buildIndex(); staticService.buildOther(); OutputStream outputStream = null; try { org.springframework.core.io.Resource resource = new ClassPathResource( CommonAttributes.SHOPXX_PROPERTIES_PATH); Properties properties = PropertiesLoaderUtils.loadProperties(resource); String templateUpdateDelay = properties.getProperty("template.update_delay"); String messageCacheSeconds = properties.getProperty("message.cache_seconds"); if (setting.getIsDevelopmentEnabled()) { if (!templateUpdateDelay.equals("0") || !messageCacheSeconds.equals("0")) { outputStream = new FileOutputStream(resource.getFile()); properties.setProperty("template.update_delay", "0"); properties.setProperty("message.cache_seconds", "0"); properties.store(outputStream, "SHOP++ PROPERTIES"); } } else { if (templateUpdateDelay.equals("0") || messageCacheSeconds.equals("0")) { outputStream = new FileOutputStream(resource.getFile()); properties.setProperty("template.update_delay", "3600"); properties.setProperty("message.cache_seconds", "3600"); properties.store(outputStream, "SHOP++ PROPERTIES"); } } } catch (Exception e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(outputStream); } addFlashMessage(redirectAttributes, SUCCESS_MESSAGE); return "redirect:edit.jhtml"; }