List of usage examples for org.springframework.web.multipart MultipartFile getSize
long getSize();
From source file:com.siblinks.ws.service.impl.UploadEssayServiceImpl.java
/** * {@inheritDoc}//w w w.ja va 2s .co m */ @Override @RequestMapping(value = "/upload", method = RequestMethod.POST) public ResponseEntity<Response> upload(@RequestParam("name") final String name, @RequestParam("userId") final String userId, @RequestParam("userType") final String userType, @RequestParam("file") final MultipartFile file) { SimpleResponse simpleResponse = null; boolean status = true; String statusMessage = null; try { if (!AuthenticationFilter.isAuthed(context)) { simpleResponse = new SimpleResponse(SibConstants.FAILURE, "Authentication required."); return new ResponseEntity<Response>(simpleResponse, HttpStatus.FORBIDDEN); } if (!file.isEmpty()) { ResponseEntity<Response> msg = uploadFile(file); String urlFile = (String) msg.getBody().getRequest_data_result(); String review = env.getProperty("directoryReviewDefaultUploadEssay"); if (msg.getBody().getStatus() == "true") { boolean msgs = true; if ("S".equalsIgnoreCase(userType)) { Object[] queryParams = { userId, name, file.getOriginalFilename(), "" + file.getSize(), file.getContentType(), urlFile, review }; msgs = dao.upload(SibConstants.SqlMapper.SQL_STUDENT_UPLOAD, queryParams, file); } else if ("M".equalsIgnoreCase(userType)) { Object[] queryParamsM = { "" + userId, file.getSize() }; dao.upload(SibConstants.SqlMapper.SQL_MENTOR_UPLOAD, queryParamsM, file); } if (msgs) { statusMessage = "Done"; } else { status = false; statusMessage = "You failed to upload "; } } else { status = false; statusMessage = (String) msg.getBody().getRequest_data_result(); } } else { status = false; statusMessage = "You failed to upload " + name + " because the file was empty."; } } catch (Exception e) { e.printStackTrace(); status = false; statusMessage = "You failed to upload " + name + " => " + e.getMessage(); logger.error(e.getMessage(), e.getCause()); } simpleResponse = new SimpleResponse("" + status, "essay", "upload", statusMessage); return new ResponseEntity<Response>(simpleResponse, HttpStatus.OK); }
From source file:com.baidu.upload.controller.ImageController.java
@RequestMapping(value = "/upload", method = RequestMethod.POST) public @ResponseBody Map<String, Object> upload(MultipartHttpServletRequest request, HttpServletResponse response, Integer reqid) { log.debug("uploadPost called"); System.out.println("id" + reqid); //????//from w w w. j av a 2 s .c om Iterator<String> itr = request.getFileNames(); MultipartFile mpf; List<Image> list = new LinkedList<Image>(); InputStream is = null; List<File> newfiles = new ArrayList<File>(); while (itr.hasNext()) { mpf = request.getFile(itr.next()); //?uuid?? String newFilenameBase = UUID.randomUUID().toString(); //???? String originalFileExtension = mpf.getOriginalFilename() .substring(mpf.getOriginalFilename().lastIndexOf(".")); //??? String newFilename = newFilenameBase + originalFileExtension; //? //String storageDirectory = request.getSession().getServletContext().getRealPath("/")+"pic"; //fileUploadDirectory = storageDirectory; String storageDirectory = fileUploadDirectory; String contentType = mpf.getContentType(); // File newFile = new File(storageDirectory + "/" + newFilename); try { //?? is = mpf.getInputStream(); byte[] bytes = FileCopyUtils.copyToByteArray(is); // mpf.transferTo(newFile); // BufferedImage thumbnail = Scalr.resize(ImageIO.read(newFile), 290); //??uuid-thumbnail.png String thumbnailFilename = newFilenameBase + "-thumbnail.png"; // File thumbnailFile = new File(storageDirectory + "/" + thumbnailFilename); ImageIO.write(thumbnail, "png", thumbnailFile); //image Image image = new Image(); //?blob image.setImgblob(bytes); //image.setName(mpf.getOriginalFilename()); image.setName(newFilename); image.setThumbnailFilename(thumbnailFilename); image.setNewFilename(newFilename); image.setContentType(contentType); image.setSize(mpf.getSize()); image.setThumbnailSize(thumbnailFile.length()); //?id int id = this.imageService.findId(); image.setId(id); //url image.setUrl("../img/picture/" + image.getId() + ".do"); image.setThumbnailUrl("../img/thumbnail/" + image.getId() + ".do"); image.setDeleteUrl("../img/delete/" + image.getId() + ".do"); image.setDeleteType("DELETE"); //? image.setReqid(reqid); image = imageService.create(image); newfiles.add(newFile); //?? list.add(image); } catch (IOException e) { log.error("Could not upload file " + mpf.getOriginalFilename(), e); } finally { IOUtils.closeQuietly(is); } } Map<String, Object> files = new HashMap<String, Object>(); files.put("files", list); return files; }
From source file:com.prcsteel.platform.account.service.impl.AccountServiceImpl.java
private void checkFile(MultipartFile file) { if (file == null) { throw new BusinessException(Constant.ERROR_MISSING_REQUIRED_PARAM, ""); }/*from w ww . j av a 2 s . c o m*/ String suffix = FileUtil.getFileSuffix(file.getOriginalFilename()); if (suffix == null || !Constant.IMAGE_SUFFIX.contains(suffix.toLowerCase())) { throw new BusinessException(Constant.ERROR_MISSING_REQUIRED_PARAM, AttachmentType.valueOf(file.getName()).getName() + "??"); } if (file.getSize() / Constant.M_SIZE > Constant.MAX_IMG_SIZE) { throw new BusinessException(Constant.ERROR_MISSING_REQUIRED_PARAM, AttachmentType.valueOf(file.getName()).getName() + "" + Constant.MAX_IMG_SIZE + "M"); } }
From source file:org.apigw.authserver.web.controller.ApplicationManagementController.java
@RequestMapping(value = "/app", method = RequestMethod.POST) public String registerApp(ModelMap model, @ModelAttribute("application") Application application, @RequestParam("certificate") MultipartFile certificate, MultipartFile icon, BindingResult result, Authentication authentication) throws IOException { UserDetails user = (UserDetails) authentication.getPrincipal(); Developer developer = appManagement.getDeveloper(user.getUsername()); log.debug("User {} registered or edited the app {}.", citizenLoggingUtil.getLogsafeSSN(user.getUsername()), application.getName());/* w ww .j a v a2 s.c om*/ if (developer == null) { return "redirect:register_developer"; } else { applicationValidator.validate(application, result); application.setRegistrationDate(new Date()); application.setState(State.REGISTRATED); application.setDeveloper(developer); Application existingApp = appManagement.getApplicationByClientId(application.getClientId()); if (existingApp != null) { result.rejectValue("clientId", "invalid.clientId", "Klient id:et finns redan registrerat, var god vlj ett annat."); } // validate icon if it exists if (application.getIcon() != null && application.getIcon().length > 0) { try { ByteArrayInputStream bis = new ByteArrayInputStream(application.getIcon()); BufferedImage bufferedImage = ImageIO.read(bis); log.info("Width: " + bufferedImage.getWidth() + " Height: " + bufferedImage.getHeight()); application.setIconContentType(icon.getContentType()); // TODO: Check width and height here! } catch (Exception e) { result.rejectValue("icon", "invalid.icon", "Ikonen r ej giltig"); } } //For now we are just allowing the addition of just one certificate List<Certificate> certs = new ArrayList<>(); if (certificate != null && certificate.getSize() > 0) { certs.add(createCertificate(certificate, result)); } if (result.hasErrors()) { List<Permission> permissions = permissionServices.getAllPermissions(); model.addAttribute("scopes", permissions); return "register_application"; } Application savedApp = appManagement.registerApplication(application); for (Certificate cert : certs) { cert.setApplication(savedApp); appManagement.saveCertificate(cert); savedApp.getCertificates().add(cert); } try { log.debug("Composing message to: {}", mailAddress); MimeMessage message = sender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message); helper.setTo(mailAddress); helper.setFrom(new InternetAddress(mailFrom)); log.debug("Creating message for existing app. User {} edited the app {}", citizenLoggingUtil.getLogsafeSSN(user.getUsername()), application.getName()); helper.setSubject("Redigerad app: " + application.getName()); helper.setText("Utvecklare med personnr " + user.getUsername() + " har redigerat appen: " + application.getName()); log.debug("Sending mail notification."); sender.send(message); } catch (Exception e) { log.error("Caught exception while trying to send email", e); } return "redirect:"; } }
From source file:Controller.ProviderController.java
@RequestMapping(value = "/Package/uploadCertificateImageProvider", method = RequestMethod.POST) public @ResponseBody String uploadCertificateImage( @RequestParam("certificateImage") MultipartFile certificateImage, HttpSession session) { try {/*from w ww .j av a2 s . c om*/ // get data from image String fileName = certificateImage.getOriginalFilename(); String fileSize = certificateImage.getSize() / 1024 + " Kb"; String fileType = certificateImage.getContentType(); byte[] bytes = certificateImage.getBytes(); FileMeta metaFile = new FileMeta(fileName, fileSize, fileType, bytes); // save temporary Image to session session.setAttribute("certificateImage", metaFile); return "{\"result\":\"success\"}"; } catch (Exception e) { String content = "Function: ProviderController - uploadCertificateImage\n" + "***Input***\n" + "certificateImage: " + certificateImage + "\n" + "**********\n" + "****Error****\n" + e.getMessage() + "\n" + "**********"; errorService.logBugWithAccount(content, session, e); return "{\"result\": \"error\"}"; } }
From source file:Controller.ProviderController.java
@RequestMapping(value = "/Package/CertificateUploading", method = RequestMethod.POST) public @ResponseBody String certificateUploading( @RequestParam("certificateImage") MultipartFile certificateImage, @RequestParam("dataJson") String data, HttpSession session) {//from www . jav a 2 s . com try { // get data from image String fileName = certificateImage.getOriginalFilename(); String fileSize = certificateImage.getSize() / 1024 + " Kb"; String fileType = certificateImage.getContentType(); byte[] bytes = certificateImage.getBytes(); FileMeta metaFile = new FileMeta(fileName, fileSize, fileType, bytes); // insert image AccountSession account = (AccountSession) session.getAttribute("account"); int providerID = account.getId(); String imageUrl = providerService.insertNewCertificate(data, metaFile, providerID); return "{\"result\":" + imageUrl + "}"; } catch (Exception e) { String content = "Function: ProviderController - certificateUploading\n" + "***Input***\n" + "certificateImage: " + certificateImage + "\n" + "**********\n" + "****Error****\n" + e.getMessage() + "\n" + "**********"; errorService.logBugWithAccount(content, session, e); return "{\"result\": \"error\"}"; } }
From source file:Controller.ProviderController.java
@RequestMapping(value = "/UploadAvatar", method = RequestMethod.POST) public @ResponseBody String saveAvatarToCrop(@RequestParam("providerImage") MultipartFile providerImage, HttpSession session) {/*from www .ja v a 2 s. c o m*/ try { // get data from image String fileName = providerImage.getOriginalFilename(); String fileType = providerImage.getContentType(); String fileSize = providerImage.getSize() / 1024 + " Kb"; byte[] imageInByte = providerImage.getBytes(); FileMeta metaFile = new FileMeta(fileName, fileSize, fileType, imageInByte); // save temporary Image to session session.setAttribute("avatarImage", metaFile); // get width and height of image InputStream in = new ByteArrayInputStream(imageInByte); BufferedImage bImageFromConvert = ImageIO.read(in); String data = "{\"width\": " + bImageFromConvert.getWidth() + ", \"height\": " + bImageFromConvert.getHeight() + "}"; return "{\"result\": " + data + "}"; } catch (IIOException ie) { return "{\"result\": \"image broken\"}"; } catch (Exception e) { String content = "Function: ProviderController - saveAvatarToCrop\n" + "***Input***\n" + "**********\n" + "****Error****\n" + e.getMessage() + "\n" + "**********"; errorService.logBugWithAccount(content, session, e); return "{\"result\": \"error\"}"; } }
From source file:com.siblinks.ws.service.impl.UploadEssayServiceImpl.java
/** * {@inheritDoc}// w w w. ja v a 2s.co m */ @Override @RequestMapping(value = "/uploadEssayStudent", method = RequestMethod.POST) public ResponseEntity<Response> uploadEssayStudent(@RequestParam("desc") final String desc, @RequestParam("userId") final String userId, @RequestParam("fileName") final String fileName, @RequestParam("title") final String title, @RequestParam("schoolId") final String schoolId, @RequestParam("majorId") final String majorId, @RequestParam("file") final MultipartFile file) { SimpleResponse simpleResponse = null; String statusMessage = ""; boolean status = true; try { if (!AuthenticationFilter.isAuthed(context)) { simpleResponse = new SimpleResponse(SibConstants.FAILURE, "Authentication required."); return new ResponseEntity<Response>(simpleResponse, HttpStatus.FORBIDDEN); } statusMessage = validateEssay(file); if (StringUtil.isNull(desc)) { statusMessage = "Essay description can't blank!"; } else { if (desc.length() > 1000) { statusMessage = "Essay description can't over 1000 characters!"; } } if (StringUtil.isNull(title)) { statusMessage = "Essay title can't blank!"; } else { if (title.length() > 250) { statusMessage = "Essay title can't over 250 characters!"; } } if (StringUtil.isNull(statusMessage)) { boolean msgs = true; List<Map<String, String>> allWordFilter = cachedDao.getAllWordFilter(); String strContent = CommonUtil.filterWord(desc, allWordFilter); String strTitle = CommonUtil.filterWord(title, allWordFilter); String strFileName = CommonUtil.filterWord(fileName, allWordFilter); Object[] queryParams = { userId, file.getInputStream(), strContent, file.getContentType(), strFileName, strTitle, file.getSize(), schoolId, majorId }; msgs = dao.insertUpdateObject(SibConstants.SqlMapper.SQL_STUDENT_UPLOAD_ESSAY, queryParams); if (msgs) { statusMessage = "Done"; } else { status = false; statusMessage = "You failed to upload "; } } else { status = false; } } catch (Exception e) { e.printStackTrace(); status = false; statusMessage = "You failed to upload " + file.getOriginalFilename() + " => " + e.getMessage(); logger.error(e.getMessage(), e.getCause()); } simpleResponse = new SimpleResponse("" + status, "essay", "upload", statusMessage); return new ResponseEntity<Response>(simpleResponse, HttpStatus.OK); }
From source file:org.apigw.authserver.web.controller.ApplicationManagementController.java
@RequestMapping(value = "/edit", method = RequestMethod.POST) public ModelAndView editApp(ModelMap model, Authentication authentication, @ModelAttribute("application") Application application, MultipartFile icon, @RequestParam(value = "certificate", required = false) MultipartFile certificate, BindingResult result) {//from ww w. ja v a 2 s .c om UserDetails user = (UserDetails) authentication.getPrincipal(); Developer developer = appManagement.getDeveloper(user.getUsername()); List<Permission> permissions = permissionServices.getAllPermissions(); log.debug("User {} registered or edited the app {}.", citizenLoggingUtil.getLogsafeSSN(user.getUsername()), application.getName()); if (developer == null) { return new ModelAndView("redirect:register_developer"); } else { applicationValidator.validate(application, result); log.info("app id: " + application.getId()); Application dbApp = appManagement.getApplication(application.getId()); if (!user.getUsername().equals(dbApp.getDeveloper().getResidentIdentificationNumber())) { throw new IllegalArgumentException( "The application developer is not the same as the logged in user"); } if (application.getIcon() == null && dbApp.getIcon() != null && dbApp.getIcon().length > 0) { application.setIcon(dbApp.getIcon()); log.debug("Icon wasn't updated this time around"); } else if (application.getIcon() != null) { log.debug("Icon was updated"); try { ByteArrayInputStream bis = new ByteArrayInputStream(application.getIcon()); BufferedImage bufferedImage = ImageIO.read(bis); log.info("Width: " + bufferedImage.getWidth() + " Height: " + bufferedImage.getHeight()); application.setIconContentType(icon.getContentType()); // TODO: Check width and height here! } catch (Exception e) { result.rejectValue("icon", "invalid.icon", "Ikonen r ej giltig"); } } application.setCertificates(dbApp.getCertificates()); application.setRegistrationDate(dbApp.getRegistrationDate()); application.setState(dbApp.getState()); application.setDeveloper(developer); //For now we are just allowing the addition of just one certificate List<Certificate> certs = new ArrayList<>(); if (certificate != null && certificate.getSize() > 0) { certs.add(createCertificate(certificate, result)); } //Error handling if (result.hasErrors()) { model.addAttribute(application); model.addAttribute("scopes", permissions); return new ModelAndView("application/edit"); } Application savedApp = appManagement.updateApplication(application); //Remove everything old. // Just allow one certificate to be set right now even though the model allows for more. //If this behavior is unwanted the GUI has to adapt for this as well as it only caters //for on certificate right now. if (certificate != null && certificate.getSize() > 0) { Set<Certificate> oldCerts = new HashSet<>(); //Clone in order to not get a concurrent modification exception for (Certificate cert : savedApp.getCertificates()) { oldCerts.add(cert); } //Remove anything old for (Certificate cert : oldCerts) { cert.setApplication(null); savedApp.getCertificates().remove(cert); appManagement.removeCertificate(cert); } //Set the new Certificate for (Certificate cert : certs) { cert.setApplication(savedApp); appManagement.saveCertificate(cert); savedApp.getCertificates().add(cert); } } try { log.debug("Composing message to: {}", mailAddress); MimeMessage message = sender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message); helper.setTo(mailAddress); helper.setFrom(new InternetAddress(mailFrom)); log.debug("Creating message for existing app. User {} edited the app {}", citizenLoggingUtil.getLogsafeSSN(user.getUsername()), application.getName()); helper.setSubject("Redigerad app: " + application.getName()); helper.setText("Utvecklare med personnr " + user.getUsername() + " har redigerat appen: " + application.getName()); log.debug("Sending mail notification."); sender.send(message); } catch (Exception e) { log.error("Caught exception while trying to send email", e); } } return new ModelAndView("redirect:/developer"); }