List of usage examples for org.springframework.web.multipart MultipartFile getSize
long getSize();
From source file:org.kuali.ole.select.controller.OleLicenseRequestController.java
/** * This method will add the agreement document to the existing list and also stores the attachment * to the specified path.// w w w . j a v a 2 s . c o m * * @param uifForm - MaintenanceDocumentForm * @return ModelAndView */ @RequestMapping(params = "methodToCall=insertAgreementDocument") public ModelAndView insertAgreementDocument(@ModelAttribute("KualiForm") UifFormBase uifForm, BindingResult result, HttpServletRequest request, HttpServletResponse response) { MaintenanceDocumentForm form = (MaintenanceDocumentForm) uifForm; MultipartFile attachmentFile = form.getAttachmentFile(); if (attachmentFile.getOriginalFilename() != null && !attachmentFile.getOriginalFilename().isEmpty()) { String selectedCollectionPath = form.getActionParamaterValue(UifParameters.SELLECTED_COLLECTION_PATH); CollectionGroup collectionGroup = form.getPostedView().getViewIndex() .getCollectionGroupByPath(selectedCollectionPath); String addLinePath = collectionGroup.getAddLineBindingInfo().getBindingPath(); Object eventObject = ObjectPropertyUtils.getPropertyValue(uifForm, addLinePath); OleAgreementDocumentMetadata oleAgreementDocumentMetadata = (OleAgreementDocumentMetadata) eventObject; oleAgreementDocumentMetadata.setCurrentTimeStamp(); String userName = GlobalVariables.getUserSession().getPrincipalName(); oleAgreementDocumentMetadata.setUploadedBy(userName); if (attachmentFile != null && !StringUtils.isBlank(attachmentFile.getOriginalFilename())) { if (attachmentFile.getSize() == 0) { GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(KRADConstants.GLOBAL_ERRORS, RiceKeyConstants.ERROR_UPLOADFILE_EMPTY, attachmentFile.getOriginalFilename()); return getUIFModelAndView(form); } else { try { oleAgreementDocumentMetadata.setAgreementFileName(attachmentFile.getOriginalFilename()); oleAgreementDocumentMetadata.setAgreementMimeType(attachmentFile.getContentType()); storeAgreementAttachment(attachmentFile); MaintenanceDocument document = (MaintenanceDocument) form.getDocument(); OleLicenseRequestBo oleLicenseRequestBo = (OleLicenseRequestBo) document .getNewMaintainableObject().getDataObject(); updateEventLogForLocation(oleLicenseRequestBo, "file", "Agreement Document uploaded - " + attachmentFile.getOriginalFilename()); } catch (Exception e) { LOG.error("Exception while storing the Agreement Document" + e); } } } } else { GlobalVariables.getMessageMap().putErrorWithoutFullErrorPath(KRADConstants.GLOBAL_MESSAGES, OLEConstants.OleLicenseRequest.ERROR_FILE_NOT_FOUND); return getUIFModelAndView(form); } return addLine(form, result, request, response); }
From source file:org.kuali.rice.krad.document.DocumentControllerServiceImpl.java
/** * Builds an attachment for the file (if any) associated with the add note instance. * * @param form form instance containing the attachment file * @param document document instance the attachment should be associated with * @param newNote note instance the attachment should be associated with * @return Attachment instance for the note, or null if no attachment file was present *///from w w w . ja va2 s .co m protected Attachment getNewNoteAttachment(DocumentFormBase form, Document document, Note newNote) { MultipartFile attachmentFile = form.getAttachmentFile(); if ((attachmentFile == null) || StringUtils.isBlank(attachmentFile.getOriginalFilename())) { return null; } if (attachmentFile.getSize() == 0) { GlobalVariables.getMessageMap().putError( String.format("%s.%s", KRADConstants.NEW_DOCUMENT_NOTE_PROPERTY_NAME, KRADConstants.NOTE_ATTACHMENT_FILE_PROPERTY_NAME), RiceKeyConstants.ERROR_UPLOADFILE_EMPTY, attachmentFile.getOriginalFilename()); return null; } String attachmentTypeCode = null; if (newNote.getAttachment() != null) { attachmentTypeCode = newNote.getAttachment().getAttachmentTypeCode(); } DocumentAuthorizer documentAuthorizer = getDocumentDictionaryService().getDocumentAuthorizer(document); if (!documentAuthorizer.canAddNoteAttachment(document, attachmentTypeCode, GlobalVariables.getUserSession().getPerson())) { throw buildAuthorizationException("annotate", document); } Attachment attachment; try { attachment = getAttachmentService().createAttachment(document.getNoteTarget(), attachmentFile.getOriginalFilename(), attachmentFile.getContentType(), (int) attachmentFile.getSize(), attachmentFile.getInputStream(), attachmentTypeCode); } catch (IOException e) { throw new RiceRuntimeException("Unable to store attachment", e); } return attachment; }
From source file:org.kuali.rice.krad.web.controller.DocumentControllerBase.java
/** * Called by the add note action for adding a note. Method validates, saves attachment and adds the * time stamp and author. Calls the UifControllerBase.addLine method to handle generic actions. * * @param uifForm - document form base containing the note instance that will be inserted into the document * @return ModelAndView/*from ww w .j ava 2s .c o m*/ */ @RequestMapping(method = RequestMethod.POST, params = "methodToCall=insertNote") public ModelAndView insertNote(@ModelAttribute("KualiForm") UifFormBase uifForm, BindingResult result, HttpServletRequest request, HttpServletResponse response) { // Get the note add line String selectedCollectionPath = uifForm.getActionParamaterValue(UifParameters.SELECTED_COLLECTION_PATH); String selectedCollectionId = uifForm.getActionParamaterValue(UifParameters.SELECTED_COLLECTION_ID); BindingInfo addLineBindingInfo = (BindingInfo) uifForm.getViewPostMetadata() .getComponentPostData(selectedCollectionId, UifConstants.PostMetadata.ADD_LINE_BINDING_INFO); String addLinePath = addLineBindingInfo.getBindingPath(); Object addLine = ObjectPropertyUtils.getPropertyValue(uifForm, addLinePath); Note newNote = (Note) addLine; newNote.setNotePostedTimestampToCurrent(); Document document = ((DocumentFormBase) uifForm).getDocument(); newNote.setRemoteObjectIdentifier(document.getNoteTarget().getObjectId()); // Get the attachment file String attachmentTypeCode = null; MultipartFile attachmentFile = uifForm.getAttachmentFile(); Attachment attachment = null; if (attachmentFile != null && !StringUtils.isBlank(attachmentFile.getOriginalFilename())) { if (attachmentFile.getSize() == 0) { GlobalVariables.getMessageMap().putError( String.format("%s.%s", KRADConstants.NEW_DOCUMENT_NOTE_PROPERTY_NAME, KRADConstants.NOTE_ATTACHMENT_FILE_PROPERTY_NAME), RiceKeyConstants.ERROR_UPLOADFILE_EMPTY, attachmentFile.getOriginalFilename()); } else { if (newNote.getAttachment() != null) { attachmentTypeCode = newNote.getAttachment().getAttachmentTypeCode(); } DocumentAuthorizer documentAuthorizer = getDocumentDictionaryService() .getDocumentAuthorizer(document); if (!documentAuthorizer.canAddNoteAttachment(document, attachmentTypeCode, GlobalVariables.getUserSession().getPerson())) { throw buildAuthorizationException("annotate", document); } try { String attachmentType = null; Attachment newAttachment = newNote.getAttachment(); if (newAttachment != null) { attachmentType = newAttachment.getAttachmentTypeCode(); } attachment = getAttachmentService().createAttachment(document.getNoteTarget(), attachmentFile.getOriginalFilename(), attachmentFile.getContentType(), (int) attachmentFile.getSize(), attachmentFile.getInputStream(), attachmentType); } catch (IOException e) { throw new RiceRuntimeException("Unable to store attachment", e); } } } Person kualiUser = GlobalVariables.getUserSession().getPerson(); if (kualiUser == null) { throw new IllegalStateException("Current UserSession has a null Person."); } newNote.setAuthorUniversalIdentifier(kualiUser.getPrincipalId()); // validate the note boolean rulePassed = KRADServiceLocatorWeb.getKualiRuleService() .applyRules(new AddNoteEvent(document, newNote)); // if the rule evaluation passed, let's add the note; otherwise, return with an error if (rulePassed) { DocumentHeader documentHeader = document.getDocumentHeader(); // adding the attachment after refresh gets called, since the attachment record doesn't get persisted // until the note does (and therefore refresh doesn't have any attachment to autoload based on the id, nor does it // autopopulate the id since the note hasn't been persisted yet) if (attachment != null) { newNote.addAttachment(attachment); } // Save the note if the document is already saved if (!documentHeader.getWorkflowDocument().isInitiated() && StringUtils.isNotEmpty(document.getNoteTarget().getObjectId()) && !(document instanceof MaintenanceDocument && NoteType.BUSINESS_OBJECT.getCode().equals(newNote.getNoteTypeCode()))) { getNoteService().save(newNote); } return addLine(uifForm, result, request, response); } else { return getUIFModelAndView(uifForm); } }
From source file:org.lazulite.boot.autoconfigure.core.web.controller.AjaxUploadController.java
/** * @param request/*from ww w.jav a2 s . c om*/ * @param files * @return */ @RequestMapping(value = "ajaxUpload", method = RequestMethod.POST) @ResponseBody public AjaxUploadResponse ajaxUpload(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "files[]", required = false) MultipartFile[] files) { //The file upload plugin makes use of an Iframe Transport module for browsers like Microsoft Internet Explorer and Opera, which do not yet support XMLHTTPRequest file uploads. response.setContentType("text/plain"); AjaxUploadResponse ajaxUploadResponse = new AjaxUploadResponse(); if (ArrayUtils.isEmpty(files)) { return ajaxUploadResponse; } for (MultipartFile file : files) { String filename = file.getOriginalFilename(); long size = file.getSize(); try { String url = FileUploadUtils.upload(request, baseDir, file, allowedExtension, maxSize, true); String deleteURL = "/ajaxUpload/delete?filename=" + URLEncoder.encode(url, Constants.ENCODING); if (ImagesUtils.isImage(filename)) { ajaxUploadResponse.add(filename, size, url, url, deleteURL); } else { ajaxUploadResponse.add(filename, size, url, deleteURL); } continue; } catch (IOException e) { LogUtils.logError("file upload error", e); ajaxUploadResponse.add(filename, size, MessageUtils.message("upload.server.error")); continue; } catch (FileUploadBase.FileSizeLimitExceededException e) { ajaxUploadResponse.add(filename, size, MessageUtils.message("upload.exceed.maxSize")); continue; } catch (InvalidExtensionException e) { e.printStackTrace(); } catch (FileNameLengthLimitExceededException e) { e.printStackTrace(); } } return ajaxUploadResponse; }
From source file:org.nextframework.bean.editors.FileEditor.java
public void setValue(Object value) { if (value instanceof MultipartFile) { MultipartFile multipartFile = (MultipartFile) value; long size = multipartFile.getSize(); try {//from w w w.j a va 2 s . c o m File file = createFile(value); String name = multipartFile.getOriginalFilename(); name = name.replace('\\', '/'); if (name.contains("/")) { name = name.substring(name.indexOf('/')); } file.setName(name); file.setContenttype(multipartFile.getContentType()); file.setContent(multipartFile.getBytes()); file.setSize(size); super.setValue(file); } catch (IOException ex) { logger.error("Cannot read contents of multipart file", ex); throw new IllegalArgumentException("Cannot read contents of multipart file: " + ex.getMessage()); } } else if (value instanceof File) { super.setValue(value); } }
From source file:org.openremote.modeler.action.FileUploadController.java
/** * upload an image.<br />/*from w w w. ja v a 2 s .co m*/ * your action should be : fileUploadController.htm?method=uploadImage&uploadFieldName=<b>your * upload Field Name</b> . * * @param request * @param response * @throws IOException */ public void uploadImage(HttpServletRequest request, HttpServletResponse response) throws IOException { String uploadFieldName = request.getParameter("uploadFieldName"); if (uploadFieldName == null || uploadFieldName.trim().length() == 0) { LOGGER.error("The action must have a parameter 'uploadFieldName'"); return; } long maxImageSize = 1024 * 1024 * 5; MultipartFile multipartFile = MultipartFileUtil.getMultipartFileFromRequest(request, uploadFieldName); if (multipartFile.getSize() == 0 || multipartFile.getSize() > maxImageSize) { return; } File file = resourceService.uploadImage(multipartFile.getInputStream(), multipartFile.getOriginalFilename()); String delimiter = ""; String escapedChar = "[ \\+\\-\\*%\\!\\(\\\"')_#;/?:&;=$,#<>]"; String fileName = file.getName(); fileName = fileName.replaceAll(escapedChar, delimiter); String extension = FilenameUtils.getExtension(fileName); fileName = fileName.replace("." + extension, ""); fileName += System.currentTimeMillis(); fileName += "." + extension; File newFile = new File(file.getParent() + File.separator + fileName); file.renameTo(newFile); if (("panelImage".equals(uploadFieldName) || "tabbarImage".equals(uploadFieldName)) && newFile.exists()) { rotateBackgroud(newFile); BufferedImage buff = ImageIO.read(newFile); response.getWriter() .print("{\"name\": \"" + resourceService.getRelativeResourcePathByCurrentAccount(newFile.getName()) + "\",\"width\":" + buff.getWidth() + ",\"height\":" + buff.getHeight() + "}"); } else { response.getWriter().print(resourceService.getRelativeResourcePathByCurrentAccount(newFile.getName())); } }
From source file:org.qifu.controller.CommonUploadDownloadAction.java
@ControllerMethodAuthority(check = true, programId = "CORE_PROGCOMM0003Q") @RequestMapping(value = "/core.commonUploadFileJson.do", method = { RequestMethod.POST }, headers = "content-type=multipart/*") public @ResponseBody DefaultControllerJsonResultObj<String> uploadFile( @RequestParam("commonUploadFile") MultipartFile file, @RequestParam("commonUploadFileType") String type, @RequestParam("commonUploadFileIsFileMode") String isFile, @RequestParam("commonUploadFileSystem") String system) { DefaultControllerJsonResultObj<String> result = this.getDefaultJsonResult("CORE_PROGCOMM0003Q"); if (!this.isAuthorizeAndLoginFromControllerJsonResult(result)) { return result; }/*from w ww .j a va2 s . c o m*/ if (null == file || file.getSize() < 1) { result.setMessage(SysMessageUtil.get(SysMsgConstants.UPLOAD_FILE_NO_SELECT)); return result; } if (file.getSize() > UPLOAD_MAX_SIZE) { result.setMessage("File max size only " + UPLOAD_MAX_SIZE + " bytes!"); return result; } if (!UploadTypes.check(type)) { result.setMessage(SysMessageUtil.get(SysMsgConstants.UPLOAD_FILE_TYPE_ERROR)); return result; } try { String uploadOid = UploadSupportUtils.create(system, type, (YES.equals(isFile) ? true : false), file.getBytes(), file.getOriginalFilename()); if (!StringUtils.isBlank(uploadOid)) { result.setSuccess(YES); result.setValue(uploadOid); result.setMessage(SysMessageUtil.get(SysMsgConstants.INSERT_SUCCESS)); } else { result.setMessage(SysMessageUtil.get(SysMsgConstants.INSERT_FAIL)); } } catch (AuthorityException | ServiceException | ControllerException e) { result.setMessage(e.getMessage().toString()); } catch (Exception e) { exceptionResult(result, e); } return result; }
From source file:org.sakaiproject.assignment2.tool.beans.UploadBean.java
/** * The user may upload either a zip archive or just the grades csv file. * This method will figure out what they uploaded and redirect to * the appropriate upload process. //www . ja va 2 s . c o m * @return */ public WorkFlowResult processUpload() { if (!AssignmentAuthoringBean.checkCsrf(csrfToken)) return WorkFlowResult.UPLOAD_FAILURE; if (uploadOptions == null || uploadOptions.assignmentId == null) { messages.addMessage(new TargettedMessage( "No assignmentId was passed " + "in the request to processUploadGradesCSV. Cannot continue.", new Object[] {}, TargettedMessage.SEVERITY_ERROR)); return WorkFlowResult.UPLOAD_FAILURE; } Assignment2 assign = assignmentLogic.getAssignmentByIdWithAssociatedData(uploadOptions.assignmentId); if (assign == null) { throw new AssignmentNotFoundException("No assignment exists with " + "the assignmentId passed to the upload via uploadOptions: " + uploadOptions.assignmentId); } boolean gbItemExists = assign.isGraded() && assign.getGradebookItemId() != null && gradebookLogic.gradebookItemExists(assign.getGradebookItemId()); if (uploads.isEmpty()) { if (assign.isGraded() && gbItemExists) { messages.addMessage(new TargettedMessage("assignment2.uploadall.alert.file_type.graded", new Object[] {}, TargettedMessage.SEVERITY_ERROR)); } else { messages.addMessage(new TargettedMessage("assignment2.uploadall.alert.file_type.ungraded", new Object[] {}, TargettedMessage.SEVERITY_ERROR)); } return WorkFlowResult.UPLOAD_FAILURE; } MultipartFile uploadedFile = uploads.get("file"); long uploadedFileSize = uploadedFile.getSize(); if (uploadedFileSize == 0) { if (assign.isGraded() && gbItemExists) { messages.addMessage(new TargettedMessage("assignment2.uploadall.alert.file_type.graded", new Object[] {}, TargettedMessage.SEVERITY_ERROR)); } else { messages.addMessage(new TargettedMessage("assignment2.uploadall.alert.file_type.ungraded", new Object[] {}, TargettedMessage.SEVERITY_ERROR)); } return WorkFlowResult.UPLOAD_FAILURE; } // double check that the file doesn't exceed our upload limit String maxFileSizeInMB = ServerConfigurationService.getString("content.upload.max", "1"); int maxFileSizeInBytes = 1024 * 1024; try { maxFileSizeInBytes = Integer.parseInt(maxFileSizeInMB) * 1024 * 1024; } catch (NumberFormatException e) { log.warn("Unable to parse content.upload.max retrieved from properties file during upload"); } if (uploadedFileSize > maxFileSizeInBytes) { messages.addMessage(new TargettedMessage("assignment2.uploadall.error.file_size", new Object[] { maxFileSizeInMB }, TargettedMessage.SEVERITY_ERROR)); return WorkFlowResult.UPLOAD_FAILURE; } boolean isZip = "application/zip".equals(uploadedFile.getContentType()) || "application/x-zip-compressed".equals(uploadedFile.getContentType()) || "application/x-zip".equals(uploadedFile.getContentType()); boolean isCsv = uploadedFile.getOriginalFilename().endsWith(".csv"); if (isZip) { return processUploadAll(uploadedFile, assign); } else if (isCsv) { // we have a separate limit for the size of the csv file int maxGradesFileSize = uploadGradesLogic.getGradesMaxFileSize(); long maxGradesSizeInBytes = 1024L * 1024L * maxGradesFileSize; if (uploadedFileSize > maxGradesSizeInBytes) { messages.addMessage(new TargettedMessage("assignment2.upload_grades.error.file_size", new Object[] { maxGradesFileSize }, TargettedMessage.SEVERITY_ERROR)); return WorkFlowResult.UPLOAD_FAILURE; } // make sure this assignment is graded and the gradebook item still exists if (!assign.isGraded()) { messages.addMessage(new TargettedMessage("assignment2.uploadall.upload_csv.ungraded", new Object[] { maxFileSizeInMB }, TargettedMessage.SEVERITY_ERROR)); return WorkFlowResult.UPLOAD_FAILURE; } else if (!gbItemExists) { messages.addMessage(new TargettedMessage("assignment2.uploadall.upload_csv.no_gb_item", new Object[] { maxFileSizeInMB }, TargettedMessage.SEVERITY_ERROR)); return WorkFlowResult.UPLOAD_FAILURE; } return processUploadGradesCSV(uploadedFile, assign); } else { if (assign.isGraded() && gbItemExists) { messages.addMessage(new TargettedMessage("assignment2.uploadall.alert.file_type.graded", new Object[] {}, TargettedMessage.SEVERITY_ERROR)); } else { messages.addMessage(new TargettedMessage("assignment2.uploadall.alert.file_type.ungraded", new Object[] {}, TargettedMessage.SEVERITY_ERROR)); } return WorkFlowResult.UPLOAD_FAILURE; } }
From source file:org.sakaiproject.lessonbuildertool.tool.beans.SimplePageBean.java
private boolean uploadSizeOk(MultipartFile file) { long uploadedFileSize = file.getSize(); return uploadSizeOk(uploadedFileSize); }
From source file:org.sakaiproject.lessonbuildertool.tool.beans.SimplePageBean.java
private String uploadFile(String collectionId) { String name = null;/*from w ww . j a va 2s.c o m*/ String mimeType = null; MultipartFile file = null; if (multipartMap.size() > 0) { // user specified a file, create it file = multipartMap.values().iterator().next(); } if (file != null) { // uploadsizeok would otherwise complain about 0 length file. For // this case it's valid. Means no file. if (file.getSize() == 0) return null; if (!uploadSizeOk(file)) return null; try { contentHostingService.checkCollection(collectionId); } catch (Exception ex) { try { ContentCollectionEdit edit = contentHostingService.addCollection(collectionId); edit.getPropertiesEdit().addProperty(ResourceProperties.PROP_DISPLAY_NAME, "LB-CSS"); contentHostingService.commitCollection(edit); } catch (Exception e) { setErrMessage(messageLocator.getMessage("simplepage.permissions-general")); return null; } } //String collectionId = getCollectionIdfalse); // user specified a file, create it name = file.getOriginalFilename(); if (name == null || name.length() == 0) name = file.getName(); int i = name.lastIndexOf("/"); if (i >= 0) name = name.substring(i + 1); String base = name; String extension = ""; i = name.lastIndexOf("."); if (i > 0) { base = name.substring(0, i); extension = name.substring(i + 1); } mimeType = file.getContentType(); try { ContentResourceEdit res = contentHostingService .addResource(collectionId, fixFileName(collectionId, Validator.escapeResourceName(base), Validator.escapeResourceName(extension)), "", MAXIMUM_ATTEMPTS_FOR_UNIQUENESS); res.setContentType(mimeType); res.setContent(file.getInputStream()); try { contentHostingService.commitResource(res, NotificationService.NOTI_NONE); // there's a bug in the kernel that can cause // a null pointer if it can't determine the encoding // type. Since we want this code to work on old // systems, work around it. } catch (java.lang.NullPointerException e) { setErrMessage(messageLocator.getMessage("simplepage.resourcepossibleerror")); } return res.getId(); } catch (org.sakaiproject.exception.OverQuotaException ignore) { setErrMessage(messageLocator.getMessage("simplepage.overquota")); return null; } catch (Exception e) { setErrMessage(messageLocator.getMessage("simplepage.resourceerror").replace("{}", e.toString())); log.error("addMultimedia error 1 " + e); return null; } } else { return null; } }