List of usage examples for org.springframework.web.multipart MultipartFile getSize
long getSize();
From source file:org.egov.council.web.controller.CouncilPreambleController.java
@RequestMapping(value = "/update", method = RequestMethod.POST) public String update(@Valid @ModelAttribute final CouncilPreamble councilPreamble, final Model model, @RequestParam final MultipartFile attachments, final BindingResult errors, final HttpServletRequest request, final RedirectAttributes redirectAttrs, @RequestParam String workFlowAction) { validatePreamble(councilPreamble, errors); if (errors.hasErrors()) { prepareWorkFlowOnLoad(model, councilPreamble); model.addAttribute(CURRENT_STATE, councilPreamble.getCurrentState().getValue()); return COUNCILPREAMBLE_EDIT; }//from w w w. ja va 2 s .c om List<Boundary> wardIdsList = new ArrayList<>(); String selectedWardIds = request.getParameter("wardsHiddenIds"); if (StringUtils.isNotEmpty(selectedWardIds)) { String[] wardIds = selectedWardIds.split(","); for (String wrdId : wardIds) { if (StringUtils.isNotEmpty(wrdId)) wardIdsList.add(boundaryService.getBoundaryById(Long.valueOf(wrdId))); } } councilPreamble.setWards(wardIdsList); if (attachments != null && attachments.getSize() > 0) { try { councilPreamble.setFilestoreid( fileStoreService.store(attachments.getInputStream(), attachments.getOriginalFilename(), attachments.getContentType(), CouncilConstants.MODULE_NAME)); } catch (IOException e) { LOGGER.error("Error in loading Employee photo" + e.getMessage(), e); } } Long approvalPosition = 0l; String approvalComment = StringUtils.EMPTY; String message = StringUtils.EMPTY; String nextDesignation = ""; String approverName = ""; if (request.getParameter(APPROVAL_COMENT) != null) approvalComment = request.getParameter(APPROVAL_COMENT); if (request.getParameter(WORK_FLOW_ACTION) != null) workFlowAction = request.getParameter(WORK_FLOW_ACTION); if (request.getParameter(APPROVAL_POSITION) != null && !request.getParameter(APPROVAL_POSITION).isEmpty()) approvalPosition = Long.valueOf(request.getParameter(APPROVAL_POSITION)); if (request.getParameter("approverName") != null) approverName = request.getParameter("approverName"); if (request.getParameter("nextDesignation") == null) nextDesignation = StringUtils.EMPTY; else nextDesignation = request.getParameter("nextDesignation"); councilPreambleService.update(councilPreamble, approvalPosition, approvalComment, workFlowAction); if (null != workFlowAction) { if (CouncilConstants.WF_STATE_REJECT.equalsIgnoreCase(workFlowAction)) { message = getMessage("msg.councilPreamble.reject", nextDesignation, approverName, councilPreamble); } else if (CouncilConstants.WF_APPROVE_BUTTON.equalsIgnoreCase(workFlowAction)) { message = getMessage("msg.councilPreamble.success", nextDesignation, approverName, councilPreamble); } else if (CouncilConstants.WF_FORWARD_BUTTON.equalsIgnoreCase(workFlowAction)) { message = getMessage("msg.councilPreamble.forward", nextDesignation, approverName, councilPreamble); } else if (CouncilConstants.WF_PROVIDE_INFO_BUTTON.equalsIgnoreCase(workFlowAction)) { message = getMessage("msg.councilPreamble.moreInfo", nextDesignation, approverName, councilPreamble); } redirectAttrs.addFlashAttribute(MESSAGE2, message); } return REDIRECT_COUNCILPREAMBLE_RESULT + councilPreamble.getId(); }
From source file:org.egov.ptis.domain.service.exemption.TaxExemptionService.java
private void replaceDoc(final PropertyImpl property, final Document applicationDocument) { for (MultipartFile mp : applicationDocument.getFile()) { if (mp.getSize() != 0) { for (Document document : property.getTaxExemptionDocuments()) { if (document.getType().getName().equals(applicationDocument.getType().getName())) { document.setFiles(propertyService.addToFileStore(applicationDocument.getFile())); }/*from w ww. j a v a2 s .c o m*/ } } } }
From source file:org.esupportail.pay.web.admin.PayEvtController.java
@RequestMapping(value = "/{id}/addLogoFile", method = RequestMethod.POST, produces = "text/html") @PreAuthorize("hasPermission(#id, 'manage')") public String addLogoFile(@PathVariable("id") Long id, UploadFile uploadFile, BindingResult bindingResult, Model uiModel, HttpServletRequest request) throws IOException { if (bindingResult.hasErrors()) { log.warn(bindingResult.getAllErrors()); return "redirect:/admin/evts/" + id.toString(); }//from w w w . java 2 s. c o m uiModel.asMap().clear(); // get PosteCandidature from id PayEvt evt = PayEvt.findPayEvt(id); MultipartFile file = uploadFile.getLogoFile(); // sometimes file is null here, but I don't know how to reproduce this issue ... maybe that can occur only with some specifics browsers ? if (file != null) { Long fileSize = file.getSize(); //String contentType = file.getContentType(); //String filename = file.getOriginalFilename(); InputStream inputStream = file.getInputStream(); //byte[] bytes = IOUtils.toByteArray(inputStream); evt.getLogoFile().setBinaryFileStream(inputStream, fileSize); evt.getLogoFile().persist(); } return "redirect:/admin/evts/" + id.toString(); }
From source file:org.esupportail.publisher.service.FileService.java
private String uploadResource(final Long entityId, final String name, final MultipartFile file, final FileUploadHelper fileUploadHelper) throws MultipartException { // Checking size if (file.getSize() > fileUploadHelper.getFileMaxSize()) { throw new MaxUploadSizeExceededException(fileUploadHelper.getFileMaxSize()); }/* w ww . ja v a 2 s . co m*/ // Checking ContentType Pair<Boolean, MultipartException> isAuthorized = isAuthorizedMimeType(file, fileUploadHelper); Assert.notNull(isAuthorized.getFirst()); if (!isAuthorized.getFirst()) { if (isAuthorized.getSecond() != null) throw isAuthorized.getSecond(); return null; } try { final String fileExt = Files.getFileExtension(file.getOriginalFilename()).toLowerCase(); String fname = new SimpleDateFormat("yyyyMMddHHmmss'." + fileExt + "'").format(new Date()); // if (name != null && name.length() > 0 ) { // fname = Files.getNameWithoutExtension(name) + "-" + fname; // } final String internPath = fileUploadHelper.getUploadDirectoryPath(); final String relativPath = String.valueOf(entityId).hashCode() + File.separator + df.format(new Date()) + File.separator; final String path = internPath + relativPath; File inFile = new File(path + fname); // checking if path is existing if (!inFile.getParentFile().exists()) { boolean error = !inFile.getParentFile().mkdirs(); if (error) { log.error("Can't create directory {} to upload file, track error!", inFile.getParentFile().getPath()); return null; } } // checking if file exist else renaming file name int i = 1; while (inFile.exists()) { inFile = new File(path + i + fname); i++; } log.debug("Uploading file as {}", inFile.getPath()); // start upload file.transferTo(inFile); return fileUploadHelper.getUrlResourceMapping() + relativPath + fname; } catch (Exception e) { log.error("File Upload error", e); return null; } }
From source file:org.exem.flamingo.web.filesystem.s3.S3BrowserServiceImpl.java
@Override public void upload(String bucketName, String key, MultipartFile file) throws IOException { ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentLength(file.getSize()); PutObjectRequest request = new PutObjectRequest(bucketName, key, file.getInputStream(), metadata); this.s3.putObject(request); }
From source file:org.flowable.rest.service.api.identity.UserPictureResource.java
@ApiOperation(value = "Updating a users picture", tags = { "Users" }, consumes = "multipart/form-data", notes = "The request should be of type multipart/form-data. There should be a single file-part included with the binary value of the picture. On top of that, the following additional form-fields can be present:\n" + "\n" + "mimeType: Optional mime-type for the uploaded picture. If omitted, the default of image/jpeg is used as a mime-type for the picture.") @ApiResponses(value = {// www . j ava 2 s . c om @ApiResponse(code = 200, message = "Indicates the user was found and the picture has been updated. The response-body is left empty intentionally."), @ApiResponse(code = 404, message = "Indicates the requested user was not found.") }) @RequestMapping(value = "/identity/users/{userId}/picture", method = RequestMethod.PUT) public void updateUserPicture(@ApiParam(name = "userId") @PathVariable String userId, HttpServletRequest request, HttpServletResponse response) { User user = getUserFromRequest(userId); if (request instanceof MultipartHttpServletRequest == false) { throw new FlowableIllegalArgumentException("Multipart request is required"); } MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; if (multipartRequest.getFileMap().size() == 0) { throw new FlowableIllegalArgumentException("Multipart request with file content is required"); } MultipartFile file = multipartRequest.getFileMap().values().iterator().next(); try { String mimeType = file.getContentType(); int size = ((Long) file.getSize()).intValue(); // Copy file-body in a bytearray as the engine requires this ByteArrayOutputStream bytesOutput = new ByteArrayOutputStream(size); IOUtils.copy(file.getInputStream(), bytesOutput); Picture newPicture = new Picture(bytesOutput.toByteArray(), mimeType); identityService.setUserPicture(user.getId(), newPicture); response.setStatus(HttpStatus.NO_CONTENT.value()); } catch (Exception e) { throw new FlowableException("Error while reading uploaded file: " + e.getMessage(), e); } }
From source file:org.hoteia.qalingo.core.service.WebBackofficeService.java
public Retailer createOrUpdateRetailer(Retailer retailer, final RetailerForm retailerForm) throws Exception { if (retailer == null) { retailer = new Retailer(); }/* w w w.j a v a2 s . c om*/ if (StringUtils.isNotEmpty(retailerForm.getCode())) { retailer.setCode(CoreUtil.cleanEntityCode(retailerForm.getCode())); } if (StringUtils.isNotEmpty(retailerForm.getName())) { retailer.setName(retailerForm.getName()); } retailer.setDescription(retailerForm.getDescription()); RetailerAddress retailerAddress = retailer.getDefaultAddress(); if (retailerAddress == null) { retailerAddress = new RetailerAddress(); retailer.getAddresses().add(retailerAddress); } retailerAddress.setAddress1(retailerForm.getAddress1()); retailerAddress.setAddress2(retailerForm.getAddress2()); retailerAddress.setAddressAdditionalInformation(retailerForm.getAddressAdditionalInformation()); retailerAddress.setPostalCode(retailerForm.getPostalCode()); retailerAddress.setCity(retailerForm.getCity()); retailerAddress.setStateCode(retailerForm.getStateCode()); retailerAddress.setCountryCode(retailerForm.getCountryCode()); retailerAddress.setPhone(retailerForm.getPhone()); retailerAddress.setFax(retailerForm.getFax()); retailerAddress.setMobile(retailerForm.getMobile()); retailerAddress.setEmail(retailerForm.getEmail()); retailerAddress.setWebsite(retailerForm.getWebsite()); retailer.setBrand(retailerForm.isBrand()); retailer.setCorner(retailerForm.isCorner()); retailer.setEcommerce(retailerForm.isEcommerce()); retailer.setOfficialRetailer(retailerForm.isOfficialRetailer()); // if(StringUtils.isNotBlank(retailerForm.getWarehouseId())){ // final Warehouse warehouse = warehouseService.getWarehouseById(retailerForm.getWarehouseId()); // if(warehouse != null){ // retailer.setWarehouse(warehouse); // } // } else { // retailer.setWarehouse(null); // } MultipartFile multipartFile = retailerForm.getFile(); if (multipartFile != null && multipartFile.getSize() > 0) { UUID uuid = UUID.randomUUID(); String pathRetailerLogoImage = new StringBuilder(uuid.toString()) .append(System.getProperty("file.separator")) .append(FilenameUtils.getExtension(multipartFile.getOriginalFilename())).toString(); String absoluteFilePath = retailerService.buildRetailerLogoFilePath(retailer, pathRetailerLogoImage); String absoluteFolderPath = absoluteFilePath.replace(pathRetailerLogoImage, ""); InputStream inputStream = multipartFile.getInputStream(); File fileLogo = null; File folderLogo = null; try { folderLogo = new File(absoluteFolderPath); folderLogo.mkdirs(); fileLogo = new File(absoluteFilePath); } catch (Exception e) { // } if (fileLogo != null) { OutputStream outputStream = new FileOutputStream(fileLogo); int readBytes = 0; byte[] buffer = new byte[8192]; while ((readBytes = inputStream.read(buffer, 0, 8192)) != -1) { outputStream.write(buffer, 0, readBytes); } outputStream.close(); inputStream.close(); retailer.setLogo(pathRetailerLogoImage); } } return retailerService.saveOrUpdateRetailer(retailer); }
From source file:org.hoteia.qalingo.web.mvc.controller.catalog.AssetController.java
@RequestMapping(value = BoUrls.ASSET_EDIT_URL, method = RequestMethod.POST) public ModelAndView assetEdit(final HttpServletRequest request, final HttpServletResponse response, @Valid AssetForm assetForm, BindingResult result, Model model) throws Exception { if (result.hasErrors()) { return display(request, response, model); }// w w w . j ava 2 s. c o m final String currentAssetId = assetForm.getId(); final Asset asset = productMarketingService.getProductMarketingAssetById(currentAssetId); MultipartFile multipartFile = assetForm.getFile(); if (multipartFile != null) { long size = multipartFile.getSize(); asset.setFileSize(size); } try { if (multipartFile.getSize() > 0) { String pathProductMarketingImage = multipartFile.getOriginalFilename(); String assetFileRootPath = engineSettingService.getSettingAssetFileRootPath().getDefaultValue(); assetFileRootPath.replaceAll("\\\\", "/"); if (assetFileRootPath.endsWith("/")) { assetFileRootPath = assetFileRootPath.substring(0, assetFileRootPath.length() - 1); } String assetProductMarketingFilePath = engineSettingService .getSettingAssetProductMarketingFilePath().getDefaultValue(); assetProductMarketingFilePath.replaceAll("\\\\", "/"); if (assetProductMarketingFilePath.endsWith("/")) { assetProductMarketingFilePath = assetProductMarketingFilePath.substring(0, assetProductMarketingFilePath.length() - 1); } if (!assetProductMarketingFilePath.startsWith("/")) { assetProductMarketingFilePath = "/" + assetProductMarketingFilePath; } String absoluteFilePath = assetFileRootPath + assetProductMarketingFilePath + "/" + asset.getType().toLowerCase() + "/" + pathProductMarketingImage; InputStream inputStream = multipartFile.getInputStream(); URI url = new URI(absoluteFilePath); File fileAsset; try { fileAsset = new File(url); } catch (IllegalArgumentException e) { fileAsset = new File(url.getPath()); } OutputStream outputStream = new FileOutputStream(fileAsset); int readBytes = 0; byte[] buffer = new byte[8192]; while ((readBytes = inputStream.read(buffer, 0, 8192)) != -1) { outputStream.write(buffer, 0, readBytes); } outputStream.close(); inputStream.close(); asset.setPath(pathProductMarketingImage); } // UPDATE ASSET webBackofficeService.createOrUpdateProductMarketingAsset(asset, assetForm); } catch (Exception e) { logger.error("Can't save/update asset file!", e); } final String urlRedirect = backofficeUrlService.generateUrl(BoUrls.ASSET_DETAILS, requestUtil.getRequestData(request), asset); return new ModelAndView(new RedirectView(urlRedirect)); }
From source file:org.kuali.coeus.propdev.impl.attachment.Narrative.java
@Override public void init(MultipartFile multipartFile) throws Exception { this.name = multipartFile.getOriginalFilename(); this.size = multipartFile.getSize(); NarrativeAttachment attachment = new NarrativeAttachment(); attachment.setType(multipartFile.getContentType()); attachment.setData(multipartFile.getBytes()); attachment.setName(multipartFile.getOriginalFilename()); setNarrativeAttachment(attachment);/* ww w.j a v a2 s . c om*/ }
From source file:org.kuali.coeus.propdev.impl.person.attachment.ProposalPersonBiography.java
@Override public void init(MultipartFile multipartFile) throws Exception { this.name = multipartFile.getOriginalFilename(); this.size = multipartFile.getSize(); ProposalPersonBiographyAttachment attachment = new ProposalPersonBiographyAttachment(); attachment.setType(multipartFile.getContentType()); attachment.setData(multipartFile.getBytes()); attachment.setName(multipartFile.getOriginalFilename()); setPersonnelAttachment(attachment);/*from www . ja v a 2s . c o m*/ }