List of usage examples for org.springframework.web.multipart MultipartFile getSize
long getSize();
From source file:org.apache.rave.portal.service.impl.DefaultOmdlService.java
@Override public Page importOmdl(MultipartFile multipartFile, String pageName) throws DuplicateItemException { Page page = null;//from w w w. ja v a2 s .c o m OmdlInputAdapter omdlInputAdapter = new OmdlInputAdapter(); File temp = null; String xml = null; try { if (multipartFile != null) { if (multipartFile.getSize() > 0) { String tempUploadFolder = System.getProperty("java.io.tmpdir"); temp = new File(tempUploadFolder, multipartFile.getOriginalFilename()); multipartFile.transferTo(temp); xml = FileUtils.readFileToString(temp); } } } catch (IllegalStateException e) { logger.error(e.getMessage()); throw new RuntimeException(e); } catch (IOException e) { logger.error(e.getMessage()); throw new RuntimeException(e); } Document root = initializeBuilder(xml); if (root != null) { try { parseOmdlFile(root, omdlInputAdapter); } catch (BadOmdlXmlFormatException e) { logger.error(e.getMessage()); throw new RuntimeException(e); } } page = pageService.addNewUserPage(pageName, omdlInputAdapter.getLayoutCode()); switch (page.getRegions().size()) { case 1: populateRegionWidgets(page, omdlInputAdapter.getAllUrls(), page.getRegions().get(0).getId()); break; case 2: populateRegionWidgets(page, omdlInputAdapter.getAllLeftUrls(), page.getRegions().get(0).getId()); populateRegionWidgets(page, omdlInputAdapter.getAllRightUrls(), page.getRegions().get(1).getId()); break; case 3: populateRegionWidgets(page, omdlInputAdapter.getAllLeftUrls(), page.getRegions().get(0).getId()); populateRegionWidgets(page, omdlInputAdapter.getAllCenterUrls(), page.getRegions().get(1).getId()); populateRegionWidgets(page, omdlInputAdapter.getAllRightUrls(), page.getRegions().get(2).getId()); break; case 4: populateRegionWidgets(page, omdlInputAdapter.getAllLeftUrls(), page.getRegions().get(0).getId()); populateRegionWidgets(page, omdlInputAdapter.getAllCenterUrls(), page.getRegions().get(1).getId()); populateRegionWidgets(page, omdlInputAdapter.getAllRightUrls(), page.getRegions().get(2).getId()); populateRegionWidgets(page, omdlInputAdapter.getAllUnknownUrls(), page.getRegions().get(3).getId()); break; default: // there are no layouts with more than 4 regions at present } return page; }
From source file:org.auscope.portal.server.web.controllers.GridSubmitController.java
/** * Processes a file upload request returning a JSON object which indicates * whether the upload was successful and contains the filename and file * size./* ww w .ja v a 2 s . c o m*/ * * @param request The servlet request * @param response The servlet response containing the JSON data * * @return null */ @RequestMapping("/uploadFile.do") public ModelAndView uploadFile(HttpServletRequest request, HttpServletResponse response) { logger.debug("Entering upload.do "); String jobInputDir = (String) request.getSession().getAttribute("localJobInputDir"); MultipartHttpServletRequest mfReq = (MultipartHttpServletRequest) request; String jobType = (String) mfReq.getParameter("jobType"); String subJobId = (String) mfReq.getParameter("subJobId"); boolean success = true; String error = null; FileInformation fileInfo = null; String destinationPath = null; MultipartFile f = mfReq.getFile("file"); if (f != null) { String fileType = checkFileType(f.getOriginalFilename()); //check if multiJob or not if (jobType.equals("single") || subJobId.equals(GridSubmitController.FOR_ALL)) { logger.debug("uploading file for single job "); subJobId = GridSubmitController.FOR_ALL; if (fileType.equals(GridSubmitController.TABLE_DIR)) { destinationPath = jobInputDir + GridSubmitController.TABLE_DIR + File.separator; } else { destinationPath = jobInputDir + GridSubmitController.RINEX_DIR + File.separator; } } else { logger.debug("uploading file for multi job "); String subJobInputDir = jobInputDir + subJobId.trim() + File.separator; if (createLocalSubJobDir(request, subJobInputDir, fileType, subJobId.trim())) { if (fileType.equals(GridSubmitController.TABLE_DIR)) { destinationPath = subJobInputDir + GridSubmitController.TABLE_DIR + File.separator; } else { destinationPath = subJobInputDir + GridSubmitController.RINEX_DIR + File.separator; } } else { logger.error("Could not create local subJob Directories."); success = false; error = new String("Could not create local subJob Directories."); } } if (jobInputDir != null && success) { logger.info("Saving uploaded file " + f.getOriginalFilename()); //TO-DO allow to upload on tables directory as well. GUI functions to be added. File destination = new File(destinationPath + f.getOriginalFilename()); if (destination.exists()) { logger.debug("Will overwrite existing file."); } try { f.transferTo(destination); } catch (IOException e) { logger.error("Could not move file: " + e.getMessage()); success = false; error = new String("Could not process file."); } fileInfo = new FileInformation(f.getOriginalFilename(), f.getSize()); } else { logger.error("Input directory not found or couldn't be created in current session!"); success = false; error = new String("Internal error. Please reload the page."); } } else { logger.error("No file parameter provided."); success = false; error = new String("Invalid request."); } // We cannot use jsonView here since this is a file upload request and // ExtJS uses a hidden iframe which receives the response. response.setContentType("text/html"); response.setStatus(HttpServletResponse.SC_OK); try { PrintWriter pw = response.getWriter(); pw.print("{success:'" + success + "'"); if (error != null) { pw.print(",error:'" + error + "'"); } if (fileInfo != null) { pw.print(",name:'" + fileInfo.getName() + "',size:" + fileInfo.getSize() + ",subJob:'" + subJobId + "'"); } pw.print("}"); pw.flush(); } catch (IOException e) { logger.error(e.getMessage()); } return null; }
From source file:org.broadleafcommerce.cms.admin.server.handler.StaticAssetCustomPersistenceHandler.java
@Override public Entity add(PersistencePackage persistencePackage, DynamicEntityDao dynamicEntityDao, RecordHelper helper) throws ServiceException { if (!persistencePackage.getEntity().isMultiPartAvailableOnThread()) { throw new ServiceException("Could not detect an uploaded file."); }/* w ww.j ava 2s . c o m*/ MultipartFile upload = UploadedFile.getUpload().get("file"); Entity entity = persistencePackage.getEntity(); try { StaticAsset adminInstance; try { ImageMetadata metadata = imageArtifactProcessor.getImageMetadata(upload.getInputStream()); adminInstance = new ImageStaticAssetImpl(); ((ImageStaticAsset) adminInstance).setWidth(metadata.getWidth()); ((ImageStaticAsset) adminInstance).setHeight(metadata.getHeight()); } catch (Exception e) { //must not be an image stream adminInstance = new StaticAssetImpl(); } Map<String, FieldMetadata> entityProperties = getMergedProperties(); adminInstance = (StaticAsset) helper.createPopulatedInstance(adminInstance, entity, entityProperties, false); String fileName = getFileName(upload.getOriginalFilename()); if (StringUtils.isEmpty(adminInstance.getName())) { adminInstance.setName(fileName); } if (StringUtils.isEmpty(adminInstance.getFullUrl())) { adminInstance.setFullUrl("/" + fileName); } adminInstance.setFileSize(upload.getSize()); Collection mimeTypes = MimeUtil.getMimeTypes(upload.getOriginalFilename()); if (!mimeTypes.isEmpty()) { MimeType mimeType = (MimeType) mimeTypes.iterator().next(); adminInstance.setMimeType(mimeType.toString()); } else { mimeTypes = MimeUtil.getMimeTypes(upload.getInputStream()); if (!mimeTypes.isEmpty()) { MimeType mimeType = (MimeType) mimeTypes.iterator().next(); adminInstance.setMimeType(mimeType.toString()); } } String extension = upload.getOriginalFilename() .substring(upload.getOriginalFilename().lastIndexOf('.') + 1, upload.getOriginalFilename().length()) .toLowerCase(); adminInstance.setFileExtension(extension); String fullUrl = adminInstance.getFullUrl(); if (!fullUrl.startsWith("/")) { fullUrl = '/' + fullUrl; } if (fullUrl.lastIndexOf('.') < 0) { fullUrl += '.' + extension; } adminInstance.setFullUrl(fullUrl); adminInstance = staticAssetService.addStaticAsset(adminInstance, getSandBox()); Entity adminEntity = helper.getRecord(entityProperties, adminInstance, null, null); StaticAssetStorage storage = staticAssetStorageService.create(); storage.setStaticAssetId(adminInstance.getId()); Blob uploadBlob = staticAssetStorageService.createBlob(upload); storage.setFileData(uploadBlob); staticAssetStorageService.save(storage); return addImageRecords(adminEntity); } catch (Exception e) { LOG.error("Unable to perform add for entity: " + entity.getType()[0], e); throw new ServiceException("Unable to add entity for " + entity.getType()[0], e); } }
From source file:org.broadleafcommerce.cms.file.service.StaticAssetServiceImpl.java
@Override @Transactional(TransactionUtils.DEFAULT_TRANSACTION_MANAGER) public StaticAsset createStaticAssetFromFile(MultipartFile file, Map<String, String> properties) { try {/*from www . j a v a2 s .c om*/ return createStaticAsset(file.getInputStream(), file.getOriginalFilename(), file.getSize(), properties); } catch (IOException e) { throw new RuntimeException(e); } }
From source file:org.broadleafcommerce.openadmin.server.service.artifact.upload.UploadAddOrUpdateController.java
@Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { Map<String, String> model = new HashMap<String, String>(); String callbackName = null;/*from ww w .j a v a2 s. co m*/ try { MutablePropertyValues mpvs = new ServletRequestParameterPropertyValues(request); if (request instanceof MultipartRequest) { MultipartRequest multipartRequest = (MultipartRequest) request; bindMultipart(multipartRequest.getMultiFileMap(), mpvs); } //check for XSRF String csrfToken = (String) mpvs.getPropertyValue("csrfToken").getValue(); exploitProtectionService.compareToken(csrfToken); PersistencePackage persistencePackage = new PersistencePackage(); persistencePackage.setPersistencePerspective(new PersistencePerspective()); persistencePackage.setCsrfToken(csrfToken); String ceilingEntity = (String) mpvs.getPropertyValue("ceilingEntityFullyQualifiedClassname") .getValue(); callbackName = (String) mpvs.getPropertyValue("callbackName").getValue(); String operation = (String) mpvs.getPropertyValue("operation").getValue(); String customCriteria = (String) mpvs.getPropertyValue("customCriteria").getValue(); mpvs.removePropertyValue("ceilingEntityFullyQualifiedClassname"); mpvs.removePropertyValue("sandbox"); mpvs.removePropertyValue("callbackName"); mpvs.removePropertyValue("operation"); mpvs.removePropertyValue("customCriteria"); persistencePackage.setCeilingEntityFullyQualifiedClassname(ceilingEntity); persistencePackage.setCustomCriteria(new String[] { customCriteria }); Entity entity = new Entity(); persistencePackage.setEntity(entity); entity.setType(new String[] { ceilingEntity }); List<Property> propertyList = new ArrayList<Property>(); for (PropertyValue propertyValue : mpvs.getPropertyValues()) { if (propertyValue.getValue() instanceof MultipartFile) { MultipartFile file = (MultipartFile) propertyValue.getValue(); if (file.getSize() > maximumFileSizeInBytes) { throw new MaxUploadSizeExceededException(maximumFileSizeInBytes); } if (file.getOriginalFilename() == null || file.getOriginalFilename().indexOf(".") < 0) { throw new FileExtensionUnavailableException( "Unable to determine file extension for uploaded file. The filename for the uploaded file is: " + file.getOriginalFilename()); } Map<String, MultipartFile> fileMap = UploadedFile.getUpload(); fileMap.put(propertyValue.getName(), (MultipartFile) propertyValue.getValue()); UploadedFile.setUpload(fileMap); entity.setMultiPartAvailableOnThread(true); } else { Property property = new Property(); property.setName(propertyValue.getName()); property.setValue((String) propertyValue.getValue()); propertyList.add(property); } } entity.setProperties(propertyList.toArray(new Property[] {})); Entity result = null; if (operation.equals("add")) { result = dynamicEntityRemoteService.add(persistencePackage); } else if (operation.equals("update")) { result = dynamicEntityRemoteService.update(persistencePackage); } model.put("callbackName", callbackName); model.put("result", buildJSON(result)); return new ModelAndView("blUploadCompletedView", model); } catch (MaxUploadSizeExceededException e) { if (callbackName != null) { model.put("callbackName", callbackName); model.put("error", buildErrorJSON(e.getMessage())); } return new ModelAndView("blUploadCompletedView", model); } catch (FileExtensionUnavailableException e) { if (callbackName != null) { model.put("callbackName", callbackName); model.put("error", buildErrorJSON(e.getMessage())); } return new ModelAndView("blUploadCompletedView", model); } catch (Exception e) { e.printStackTrace(); if (callbackName != null) { model.put("callbackName", callbackName); model.put("error", buildErrorJSON(e.getMessage())); } return new ModelAndView("blUploadCompletedView", model); } finally { UploadedFile.remove(); } }
From source file:org.cloud.mblog.utils.FileUtil.java
/** * ?/*from w w w . j a v a2s. co m*/ * * @param file * @return */ public static ImageData uploadSingleFile(MultipartFile file, HttpServletRequest request, Boolean haveThumb) { if (!file.isEmpty()) { LocalDateTime now = LocalDateTime.now(); String imageRelativeFolder = getImageRelativePathByDate(now); String thumbRelativeFolder = getThumbRelativePathByDate(now); String sourceFileName = file.getOriginalFilename(); String fileType = sourceFileName.substring(sourceFileName.lastIndexOf(".") + 1); String fileName = getWidFileName(fileType); File targetFile = new File(LOCALROOT + imageRelativeFolder + File.separator + fileName); try { file.transferTo(targetFile); logger.info("Upload file path: " + targetFile.getAbsolutePath()); if (haveThumb) { File thumbFile = new File(LOCALROOT + thumbRelativeFolder + File.separator + fileName); ImageUtil.zoomImage(targetFile, thumbFile, 300); } return new ImageData(fileName, file.getSize(), imageRelativeFolder, thumbRelativeFolder); } catch (Exception e) { logger.error("error", e); } } return null; }
From source file:org.cloudifysource.rest.repo.UploadRepo.java
/** * Creates a new folder with a randomly generated name (using the UUID class) which holds the uploaded file. * The folder located at the main upload folder in {@link #baseDir}. * This uploaded file and its folder will be deleted after {@link #cleanupTimeoutMillis} millis. * * @param fileName// w w w. j a va 2 s. c om * The name of the uploaded file. * If null, the multipartFile's original file name will be used as the file's name. * @param multipartFile * The file to upload. * @return the uploaded key. * @throws RestErrorException if the file doesn't end with zip. * @throws IOException . */ public String put(final String fileName, final MultipartFile multipartFile) throws IOException, RestErrorException { String name = fileName == null ? multipartFile.getOriginalFilename() : fileName; // enforce size limit long fileSize = multipartFile.getSize(); if (fileSize > getUploadSizeLimitBytes()) { logger.warning("Upload file [" + name + "] size (" + fileSize + ") exceeded the permitted size limit (" + getUploadSizeLimitBytes() + ")."); throw new RestErrorException(CloudifyMessageKeys.UPLOAD_FILE_SIZE_LIMIT_EXCEEDED.getName(), name, fileSize, getUploadSizeLimitBytes()); } final String dirName = UUID.randomUUID().toString(); final File srcDir = new File(restUploadDir, dirName); srcDir.mkdirs(); final File storedFile = new File(srcDir, name); copyMultipartFileToLocalFile(multipartFile, storedFile); logger.finer("File [" + storedFile.getAbsolutePath() + "] uploaded."); return dirName; }
From source file:org.davidmendoza.fileUpload.web.ImageController.java
@RequestMapping(value = "/upload", method = RequestMethod.POST) public @ResponseBody Map upload(MultipartHttpServletRequest request, HttpServletResponse response) { log.debug("uploadPost called"); Iterator<String> itr = request.getFileNames(); MultipartFile mpf; List<Image> list = new LinkedList<>(); while (itr.hasNext()) { mpf = request.getFile(itr.next()); log.debug("Uploading {}", mpf.getOriginalFilename()); String newFilenameBase = UUID.randomUUID().toString(); String originalFileExtension = mpf.getOriginalFilename() .substring(mpf.getOriginalFilename().lastIndexOf(".")); String newFilename = newFilenameBase + originalFileExtension; String storageDirectory = fileUploadDirectory; String contentType = mpf.getContentType(); File newFile = new File(storageDirectory + "/" + newFilename); try {/*www . ja v a 2 s .c o m*/ mpf.transferTo(newFile); BufferedImage thumbnail = Scalr.resize(ImageIO.read(newFile), 290); String thumbnailFilename = newFilenameBase + "-thumbnail.png"; File thumbnailFile = new File(storageDirectory + "/" + thumbnailFilename); ImageIO.write(thumbnail, "png", thumbnailFile); Image image = new Image(); image.setName(mpf.getOriginalFilename()); image.setThumbnailFilename(thumbnailFilename); image.setNewFilename(newFilename); image.setContentType(contentType); image.setSize(mpf.getSize()); image.setThumbnailSize(thumbnailFile.length()); image = imageDao.create(image); image.setUrl("/picture/" + image.getId()); image.setThumbnailUrl("/thumbnail/" + image.getId()); image.setDeleteUrl("/delete/" + image.getId()); image.setDeleteType("DELETE"); list.add(image); } catch (IOException e) { log.error("Could not upload file " + mpf.getOriginalFilename(), e); } } Map<String, Object> files = new HashMap<>(); files.put("files", list); return files; }
From source file:org.egov.council.web.controller.CouncilPreambleController.java
@RequestMapping(value = "/create", method = RequestMethod.POST) public String create(@Valid @ModelAttribute final CouncilPreamble councilPreamble, final BindingResult errors, @RequestParam final MultipartFile attachments, final Model model, final HttpServletRequest request, final RedirectAttributes redirectAttrs, @RequestParam String workFlowAction) { validatePreamble(councilPreamble, errors); if (errors.hasErrors()) { prepareWorkFlowOnLoad(model, councilPreamble); return COUNCILPREAMBLE_NEW; }/*from ww w .j a v a 2s.co m*/ 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 documents" + e.getMessage(), e); } } if (isAutoPreambleNoGenEnabled()) { PreambleNumberGenerator preamblenumbergenerator = autonumberServiceBeanResolver .getAutoNumberServiceFor(PreambleNumberGenerator.class); councilPreamble.setPreambleNumber(preamblenumbergenerator.getNextNumber(councilPreamble)); } councilPreamble.setStatus(egwStatusHibernateDAO.getStatusByModuleAndCode( CouncilConstants.PREAMBLE_MODULENAME, CouncilConstants.PREAMBLE_STATUS_CREATED)); councilPreamble.setType(PreambleType.GENERAL); Long approvalPosition = 0l; String approvalComment = ""; String approverName = ""; String nextDesignation = ""; 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("approverName") != null) approverName = request.getParameter("approverName"); if (request.getParameter("nextDesignation") != null) nextDesignation = request.getParameter("nextDesignation"); if (request.getParameter(APPROVAL_POSITION) != null && !request.getParameter(APPROVAL_POSITION).isEmpty()) approvalPosition = Long.valueOf(request.getParameter(APPROVAL_POSITION)); councilPreambleService.create(councilPreamble, approvalPosition, approvalComment, workFlowAction); String message = messageSource.getMessage("msg.councilPreamble.create", new String[] { approverName.concat("~").concat(nextDesignation), councilPreamble.getPreambleNumber() }, null); redirectAttrs.addFlashAttribute(MESSAGE2, message); return REDIRECT_COUNCILPREAMBLE_RESULT + councilPreamble.getId(); }