List of usage examples for org.springframework.web.multipart MultipartFile getSize
long getSize();
From source file:com.prcsteel.platform.order.web.controller.cust.AccountController.java
private boolean checkUploadAttachment(MultipartFile file, HashMap<String, Object> result, List<MultipartFile> attachmentList) { String suffix = FileUtil.getFileSuffix(file.getOriginalFilename()); if (suffix == null || !Constant.IMAGE_SUFFIX.contains(suffix.toLowerCase())) { result.put("data", AttachmentType.valueOf(file.getName()).getName() + "??"); return false; }/*ww w. ja va 2 s. c o m*/ if (file.getSize() / Constant.M_SIZE > Constant.MAX_IMG_SIZE) { result.put("data", AttachmentType.valueOf(file.getName()).getName() + "" + Constant.MAX_IMG_SIZE + "M"); return false; } attachmentList.add(file); return true; }
From source file:com.iana.dver.controller.DverAdminController.java
@RequestMapping(value = "/admin/bulkChangeOwnerXLS", method = RequestMethod.POST) public @ResponseBody String performBulkChangeOwnerWithXLS(MultipartHttpServletRequest request, HttpServletResponse response) {// ww w . jav a 2s . c o m Iterator<String> itr = request.getFileNames(); if (!itr.hasNext()) { return "Please provide XLS file to process."; } MultipartFile bulkFile = request.getFile(itr.next()); logger.info(bulkFile.getOriginalFilename() + " uploaded!"); try { String extension = FilenameUtils.getExtension(bulkFile.getOriginalFilename()); if (extension.equalsIgnoreCase("xls")) { if (bulkFile.getSize() == 0) { return "Uploaded file should not be empty."; } if (bulkFile.getSize() > 2097152) { return "Uploaded file should not exceed 2 MB"; } Map<Integer, String[]> dversToBeProcessed = this.dverDetailsService .findDversForBulkProcessing(bulkFile.getInputStream()); if (dversToBeProcessed.isEmpty()) { return "No DVER's found for 'Change Owner Bulk Processing'."; } else { int successCount = 0; int failCount = 0; StringBuilder failDverDetails = new StringBuilder( "DVER Bulk Change Owner XLS processed successfully. <br/>"); failDverDetails.append( "Following is the list of DVER's which were not processed successfully for Bulk Change Owner: <br/>"); for (Integer dverDetailId : dversToBeProcessed.keySet()) { String[] dots = dversToBeProcessed.get(dverDetailId); RejectedDverVO rejectedDverVO = new RejectedDverVO(); rejectedDverVO.setDverDetailId(dverDetailId); rejectedDverVO.setIepdot(dots[0] != null ? dots[0] : ""); rejectedDverVO.setMcdot(dots[1] != null ? dots[1] : ""); rejectedDverVO.setIepUserId(0); rejectedDverVO.setMcUserId(0); StringBuilder errors = new StringBuilder(); validateDOTFields(rejectedDverVO, errors); if (errors.length() == 0) { this.dverDetailsService.moveRejectedDverToFound(rejectedDverVO, dverDetailId); successCount++; } else { failCount++; failDverDetails.append("(" + failCount + ") "); failDverDetails.append("DverDetailId : " + dverDetailId + " <br/>"); failDverDetails.append("MC DOT: " + rejectedDverVO.getMcdot() + " <br/>"); failDverDetails.append("IEP DOT: " + rejectedDverVO.getMcdot() + " <br/>"); failDverDetails.append("Reason for failure: " + errors.toString() + " <br/>"); } } if (failCount > 0) { logger.info("Fail DVER Notice :" + failDverDetails.toString()); DVERUtil.sendBulkUpdateFailureNotice(failDverDetails.toString()); } return "Change Owner for " + successCount + " DVER's completed successfully. Failed to complete " + failCount + " DVER's due to wrong provided values of IEP/MC DOTs"; } } else { return "The uploaded file type is not allowed."; } } catch (Exception e) { DVERUtil.sendExceptionEmails("upload method of DverAdminController \n " + e); logger.error("Error in submitEditCompanyForAdmin()....." + e); return "The uploaded file could not be processed!!"; } }
From source file:org.shaf.server.controller.CmdActionController.java
/** * Puts data to the server./* ww w .jav a 2s . c om*/ * * @param storage * the storage type. * @param alias * the data alias. * @param data * the data to upload. * @throws NetworkContentException * @throws Exception * if an error occurs. */ @RequestMapping(value = "/upload/{storage}/{alias}", method = RequestMethod.POST) public void onUpload(@PathVariable String storage, @PathVariable String alias, @RequestBody MultipartFile data) throws Exception { LOG.debug("CALL service: /cmd/upload/{" + storage + "}/{" + alias + "} with attached data."); LOG.trace("The attached data: " + data); if (data.isEmpty()) { LOG.warn("There no providing data."); } else { Firewall firewall = super.getFirewall(); String username = super.getUserName(); StorageDriver driver = OPER.getStorageDriver(firewall, username, StorageType.PROVIDER, storage); LOG.trace("Driver for uploading: " + driver); LOG.trace("Uploading data name: " + data.getName()); LOG.trace("Uploading data size: " + data.getSize()); try (InputStream in = data.getInputStream(); OutputStream out = driver.getOutputStream(alias)) { ByteStreams.copy(in, out); } catch (IOException exc) { throw exc; } } }
From source file:net.nan21.dnet.core.web.controller.upload.FileUploadController.java
/** * Generic file upload. Expects an uploaded file and a handler alias to * delegate the uploaded file processing. * //w ww.j a va2s .com * @param handler * spring bean alias of the * {@link net.nan21.dnet.core.api.service.IFileUploadService} * which should process the uploaded file * @param file * Uploaded file * @param request * @param response * @return * @throws Exception */ @RequestMapping(value = "/{handler}", method = RequestMethod.POST) @ResponseBody public String fileUpload(@PathVariable("handler") String handler, @RequestParam("file") MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws Exception { if (logger.isInfoEnabled()) { logger.info("Processing file upload request with-handler {} ", new String[] { handler }); } if (file.isEmpty()) { throw new Exception("Upload was not succesful. Try again please."); } this.prepareRequest(request, response); IFileUploadService srv = this.getFileUploadService(handler); Map<String, String> paramValues = new HashMap<String, String>(); for (String p : srv.getParamNames()) { paramValues.put(p, request.getParameter(p)); } IUploadedFileDescriptor fileDescriptor = new UploadedFileDescriptor(); fileDescriptor.setContentType(file.getContentType()); fileDescriptor.setOriginalName(file.getOriginalFilename()); fileDescriptor.setNewName(file.getName()); fileDescriptor.setSize(file.getSize()); Map<String, Object> result = srv.execute(fileDescriptor, file.getInputStream(), paramValues); this.finishRequest(); result.put("success", true); ObjectMapper mapper = getJsonMapper(); return mapper.writeValueAsString(result); }
From source file:com.epam.ta.reportportal.ws.controller.impl.LogController.java
@Override @RequestMapping(method = RequestMethod.POST, consumes = { MediaType.MULTIPART_FORM_DATA_VALUE }) @ResponseBody//from ww w . j a va 2 s . co m // @ApiOperation("Create log (batching operation)") // Specific handler should be added for springfox in case of similar POST // request mappings @ApiIgnore public ResponseEntity<BatchSaveOperatingRS> createLog(@PathVariable String projectName, @RequestPart(value = Constants.LOG_REQUEST_JSON_PART) SaveLogRQ[] createLogRQs, HttpServletRequest request, Principal principal) { String prjName = EntityUtils.normalizeProjectName(projectName); /* * Since this is multipart request we can retrieve list of uploaded * files */ Map<String, MultipartFile> uploadedFiles = getUploadedFiles(request); BatchSaveOperatingRS response = new BatchSaveOperatingRS(); EntryCreatedRS responseItem; /* Go through all provided save log request items */ for (SaveLogRQ createLogRq : createLogRQs) { try { validateSaveRQ(createLogRq); String filename = createLogRq.getFile() == null ? null : createLogRq.getFile().getName(); if (StringUtils.isEmpty(filename)) { /* * There is no filename in request. Use simple save * method */ responseItem = createLog(prjName, createLogRq, principal); } else { /* Find by request part */ MultipartFile data = findByFileName(filename, uploadedFiles); BusinessRule.expect(data, Predicates.notNull()).verify(ErrorType.BINARY_DATA_CANNOT_BE_SAVED, Suppliers.formattedSupplier("There is no request part or file with name {}", filename)); /* * If provided content type is null or this is octet * stream, try to detect real content type of binary * data */ if (!StringUtils.isEmpty(data.getContentType()) && !MediaType.APPLICATION_OCTET_STREAM_VALUE.equals(data.getContentType())) { responseItem = createLogMessageHandler.createLog(createLogRq, new BinaryData(data.getContentType(), data.getSize(), data.getInputStream()), data.getOriginalFilename(), prjName); } else { byte[] consumedData = IOUtils.toByteArray(data.getInputStream()); responseItem = createLogMessageHandler.createLog(createLogRq, new BinaryData(contentTypeResolver.detectContentType(consumedData), data.getSize(), new ByteArrayInputStream(consumedData)), data.getOriginalFilename(), prjName); } } response.addResponse(new BatchElementCreatedRS(responseItem.getId())); } catch (Exception e) { response.addResponse( new BatchElementCreatedRS(ExceptionUtils.getStackTrace(e), ExceptionUtils.getMessage(e))); } } return new ResponseEntity<>(response, HttpStatus.CREATED); }
From source file:ru.codemine.ccms.router.TaskRouter.java
@Secured("ROLE_USER") @RequestMapping(value = "/tasks/addfile", method = RequestMethod.POST) public String addFileToTask(@RequestParam("file") MultipartFile file, @RequestParam("id") Integer id) { Task task = taskService.getById(id); Employee employee = employeeService.getCurrentUser(); if (file.isEmpty()) return "redirect:/tasks/taskinfo?id=" + task.getId(); if (employee.equals(task.getCreator()) || task.getPerformers().contains(employee)) { String filename = settingsService.getStorageTasksPath() + UUID.randomUUID().toString(); String viewname = file.getOriginalFilename(); File targetFile = new File(filename); DataFile targetDataFile = new DataFile(employee); targetDataFile.setFilename(filename); targetDataFile.setViewName(viewname); targetDataFile.setSize(file.getSize()); targetDataFile.setTypeByExtension(); try {/*from ww w.ja va 2 s .c o m*/ file.transferTo(targetFile); } catch (IOException | IllegalStateException ex) { log.error(" " + viewname + ", : " + ex.getLocalizedMessage()); return "redirect:/tasks/taskinfo?id=" + task.getId(); } dataFileService.create(targetDataFile); task.getFiles().add(targetDataFile); taskService.update(task); } return "redirect:/tasks/taskinfo?id=" + task.getId(); }
From source file:com.opendesign.controller.ProductController.java
/** * ??() ?//*from w w w. j a v a 2 s.c o m*/ * * @param product * @param request * @param saveType * @return * @throws Exception */ private JsonModelAndView saveProduct(DesignWorkVO product, MultipartHttpServletRequest request, int saveType) throws Exception { /* * ?? ? ? */ boolean isUpdate = saveType == SAVE_TYPE_UPDATE; Map<String, Object> resultMap = new HashMap<String, Object>(); UserVO loginUser = CmnUtil.getLoginUser(request); if (loginUser == null || !StringUtil.isNotEmpty(loginUser.getSeq())) { resultMap.put("result", "100"); return new JsonModelAndView(resultMap); } /* ? ? */ if (isUpdate) { DesignWorkVO prevProduct = designerService.getDesignWork(product.getSeq()); if (!loginUser.getSeq().equals(prevProduct.getMemberSeq())) { resultMap.put("result", "101"); return new JsonModelAndView(resultMap); } } /* * ? ? */ MultipartFile fileUrlFile = request.getFile("fileUrlFile"); if (fileUrlFile != null) { String fileName = fileUrlFile.getOriginalFilename().toLowerCase(); if (!(fileName.endsWith(".jpg") || fileName.endsWith(".png"))) { resultMap.put("result", "202"); return new JsonModelAndView(resultMap); } } else { /* ? ? . */ if (!isUpdate) { resultMap.put("result", "201"); return new JsonModelAndView(resultMap); } } /* * license */ String license01 = request.getParameter("license01"); String license02 = request.getParameter("license02"); String license03 = request.getParameter("license03"); String license = license01 + license02 + license03; product.setLicense(license); //?? ?///// String stem = request.getParameter("origin"); if (stem == null) { product.setOriginSeq("0"); } else { product.setOriginSeq(stem); } ////////////////////////////// /* * ?? ? "0" */ String point = request.getParameter("point"); point = String.valueOf(CmnUtil.getIntValue(point)); //null--> 0 product.setPoint(point); /* * ? ? */ List<MultipartFile> productFileList = new ArrayList<MultipartFile>(); List<MultipartFile> openSourceFileList = new ArrayList<MultipartFile>(); Iterator<String> iterator = request.getFileNames(); while (iterator.hasNext()) { String fileNameKey = iterator.next(); MultipartFile reqFile = request.getFile(fileNameKey); if (reqFile != null) { boolean existProuductFile = fileNameKey.startsWith("productFile"); boolean existOpenSourceFile = fileNameKey.startsWith("openSourceFile"); if (existProuductFile || existOpenSourceFile) { long fileSize = reqFile.getSize(); if (fileSize > LIMIT_FILE_SIZE) { resultMap.put("result", "203"); resultMap.put("fileName", reqFile.getOriginalFilename()); return new JsonModelAndView(resultMap); } if (existProuductFile) { productFileList.add(reqFile); } if (existOpenSourceFile) { openSourceFileList.add(reqFile); } } } } product.setMemberSeq(loginUser.getSeq()); /* * ?? */ String fileUploadDir = CmnUtil.getFileUploadDir(request, FileUploadDomain.PRODUCT); File thumbFile = null; if (fileUrlFile != null) { String saveFileName = UUID.randomUUID().toString(); thumbFile = CmnUtil.saveFile(fileUrlFile, fileUploadDir, saveFileName); String fileUploadDbPath = CmnUtil.getFileUploadDbPath(request, thumbFile); product.setThumbUri(fileUploadDbPath); } /* * ??() */ List<DesignPreviewImageVO> productList = new ArrayList<DesignPreviewImageVO>(); List<String> productFilePaths = new ArrayList<>(); for (MultipartFile aFile : productFileList) { String saveFileName = UUID.randomUUID().toString(); File file = CmnUtil.saveFile(aFile, fileUploadDir, saveFileName); productFilePaths.add(file.getAbsolutePath()); String fileUploadDbPath = CmnUtil.getFileUploadDbPath(request, file); DesignPreviewImageVO productFile = new DesignPreviewImageVO(); productFile.setFilename(aFile.getOriginalFilename()); productFile.setFileUri(fileUploadDbPath); productList.add(productFile); } product.setImageList(productList); /* * */ List<DesignWorkFileVO> openSourceList = new ArrayList<DesignWorkFileVO>(); for (MultipartFile aFile : openSourceFileList) { String saveFileName = UUID.randomUUID().toString(); File file = CmnUtil.saveFile(aFile, fileUploadDir, saveFileName); String fileUploadDbPath = CmnUtil.getFileUploadDbPath(request, file); //openSourceFile? ??? client? . String filenameOpenSourceFile = StringUtils .stripToEmpty(request.getParameter("filename_" + aFile.getName())); DesignWorkFileVO openSourceFile = new DesignWorkFileVO(); openSourceFile.setFilename(filenameOpenSourceFile); openSourceFile.setFileUri(fileUploadDbPath); openSourceList.add(openSourceFile); } product.setFileList(openSourceList); /* * ??/? ? ? ? * ?? ? ? ? ? ? */ String thumbFilePath = ""; if (thumbFile != null) { thumbFilePath = thumbFile.getAbsolutePath(); } ThumbnailManager.resizeNClone4DesignWork(thumbFilePath, productFilePaths); /* * */ String tag = request.getParameter("tag"); if (StringUtil.isNotEmpty(tag)) { String[] tags = tag.split(","); int addIndex = 0; StringBuffer tagBuffer = new StringBuffer(); for (String aTag : tags) { if (StringUtil.isNotEmpty(aTag)) { aTag = aTag.trim(); tagBuffer.append(aTag); tagBuffer.append("|"); addIndex++; } if (addIndex >= 5) { break; } } if (addIndex > 0) { tagBuffer.insert(0, "|"); tag = tagBuffer.toString(); } } product.setTags(tag); String currentDate = Day.getCurrentTimestamp().substring(0, 12); product.setRegisterTime(currentDate); product.setUpdateTime(currentDate); String[] categoryCodes = request.getParameterValues("categoryCodes"); /* * */ if (isUpdate) { String[] removeProductSeqs = request.getParameterValues("removeProductSeq"); String[] removeOpenSourceSeqs = request.getParameterValues("removeOpenSourceSeq"); int projectSeq = service.updateProduct(product, categoryCodes, removeProductSeqs, removeOpenSourceSeqs); } else { int projectSeq = service.insertProduct(product, categoryCodes); } resultMap.put(RstConst.P_NAME, RstConst.V_SUCESS); return new JsonModelAndView(resultMap); }
From source file:com.rr.generic.ui.profile.profileController.java
/** * The 'saveProfileForm.do' POST will save the user profile form. * * @param session/* w ww . j a v a 2 s.c om*/ * @param email * @param firstName * @param lastName * @param newPassword * @param profilePhoto * @return * @throws Exception */ @RequestMapping(value = "saveProfileForm.do", method = RequestMethod.POST) public ModelAndView submitProfileForm(HttpSession session, @RequestParam String email, @RequestParam String username, @RequestParam String firstName, @RequestParam String lastName, @RequestParam String newPassword, @RequestParam(value = "profilePhoto", required = false) MultipartFile profilePhoto) throws Exception { ModelAndView mav = new ModelAndView(); mav.setViewName("/profile"); /* Get a list of completed surveys the logged in user has access to */ User userDetails = (User) session.getAttribute("userDetails"); /* Check for duplicate email address */ User existingUser = usermanager.checkDuplicateUsername(username, programId, userDetails.getId()); if (existingUser != null) { mav.addObject("existingUser", "The username is already being used by another user."); return mav; } userDetails.setFirstName(firstName); userDetails.setLastName(lastName); userDetails.setEmail(email); userDetails.setUsername(username); if (!"".equals(newPassword)) { userDetails.setPassword(newPassword); userDetails = usermanager.encryptPW(userDetails); } if (profilePhoto != null && !"".equals(profilePhoto) && profilePhoto.getSize() > 0) { String profilePhotoFileName = usermanager.saveProfilePhoto(programId, profilePhoto, userDetails); userDetails.setProfilePhoto(profilePhotoFileName); } usermanager.updateUser(userDetails); mav.addObject("savedStatus", "updated"); return mav; }
From source file:gr.abiss.calipso.tiers.controller.AbstractModelController.java
@RequestMapping(value = "{subjectId}/uploads/{propertyName}", method = { RequestMethod.POST, RequestMethod.PUT }, consumes = {}, produces = { "application/json", "application/xml" }) public @ResponseBody BinaryFile addUploadsToProperty(@PathVariable ID subjectId, @PathVariable String propertyName, MultipartHttpServletRequest request, HttpServletResponse response) { LOGGER.info("uploadPost called"); Configuration config = ConfigurationFactory.getConfiguration(); String fileUploadDirectory = config.getString(ConfigurationFactory.FILES_DIR); String baseUrl = config.getString("calipso.baseurl"); Iterator<String> itr = request.getFileNames(); MultipartFile mpf; BinaryFile bf = new BinaryFile(); try {//from ww w .j a v a 2 s . c o m if (itr.hasNext()) { mpf = request.getFile(itr.next()); LOGGER.info("Uploading {}", mpf.getOriginalFilename()); bf.setName(mpf.getOriginalFilename()); bf.setFileNameExtention( mpf.getOriginalFilename().substring(mpf.getOriginalFilename().lastIndexOf(".") + 1)); bf.setContentType(mpf.getContentType()); bf.setSize(mpf.getSize()); // request targets specific path? StringBuffer uploadsPath = new StringBuffer('/') .append(this.service.getDomainClass().getDeclaredField("PATH_FRAGMENT").get(String.class)) .append('/').append(subjectId).append("/uploads/").append(propertyName); bf.setParentPath(uploadsPath.toString()); LOGGER.info("Saving image entity with path: " + bf.getParentPath()); bf = binaryFileService.create(bf); LOGGER.info("file name: {}", bf.getNewFilename()); bf = binaryFileService.findById(bf.getId()); LOGGER.info("file name: {}", bf.getNewFilename()); File storageDirectory = new File(fileUploadDirectory + bf.getParentPath()); if (!storageDirectory.exists()) { storageDirectory.mkdirs(); } LOGGER.info("storageDirectory: {}", storageDirectory.getAbsolutePath()); LOGGER.info("file name: {}", bf.getNewFilename()); File newFile = new File(storageDirectory, bf.getNewFilename()); newFile.createNewFile(); LOGGER.info("newFile path: {}", newFile.getAbsolutePath()); Files.copy(mpf.getInputStream(), newFile.toPath(), StandardCopyOption.REPLACE_EXISTING); BufferedImage thumbnail = Scalr.resize(ImageIO.read(newFile), 290); File thumbnailFile = new File(storageDirectory, bf.getThumbnailFilename()); ImageIO.write(thumbnail, "png", thumbnailFile); bf.setThumbnailSize(thumbnailFile.length()); bf = binaryFileService.update(bf); // attach file // TODO: add/update to collection Field fileField = GenericSpecifications.getField(this.service.getDomainClass(), propertyName); Class clazz = fileField.getType(); if (BinaryFile.class.isAssignableFrom(clazz)) { T target = this.service.findById(subjectId); BeanUtils.setProperty(target, propertyName, bf); this.service.update(target); } bf.setUrl(baseUrl + "/api/rest/" + bf.getParentPath() + "/files/" + bf.getId()); bf.setThumbnailUrl(baseUrl + "/api/rest/" + bf.getParentPath() + "/thumbs/" + bf.getId()); bf.setDeleteUrl(baseUrl + "/api/rest/" + bf.getParentPath() + "/" + bf.getId()); bf.setDeleteType("DELETE"); bf.addInitialPreview("<img src=\"" + bf.getThumbnailUrl() + "\" class=\"file-preview-image\" />"); } } catch (Exception e) { LOGGER.error("Could not upload file(s) ", e); } return bf; }