Java Code Examples for org.apache.commons.fileupload.FileItem#getSize()
The following examples show how to use
org.apache.commons.fileupload.FileItem#getSize() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SaveArtifactAction.java From Knowage-Server with GNU Affero General Public License v3.0 | 6 votes |
private Content getContentFromRequest() { Content content = null; FileItem uploaded = (FileItem) getAttribute("UPLOADED_FILE"); if (uploaded != null && uploaded.getSize() > 0) { checkUploadedFile(uploaded); String fileName = GeneralUtilities.getRelativeFileNames(uploaded.getName()); content = new Content(); content.setActive(new Boolean(true)); UserProfile userProfile = (UserProfile) this.getUserProfile(); content.setCreationUser(userProfile.getUserId().toString()); content.setCreationDate(new Date()); content.setDimension(Long.toString(uploaded.getSize()/1000)+" KByte"); content.setFileName(fileName); byte[] uplCont = uploaded.get(); content.setContent(uplCont); } else { logger.debug("Uploaded file missing or it is empty"); } return content; }
Example 2
Source File: UploadDatasetFileAction.java From Knowage-Server with GNU Affero General Public License v3.0 | 6 votes |
private FileItem checkArchiveFile(FileItem uploaded) { // check if the uploaded file is empty if (uploaded.getSize() == 0) { throw new SpagoBIServiceException(getActionName(), "The uploaded file is empty"); } fileExtension = uploaded.getName().lastIndexOf('.') > 0 ? uploaded.getName().substring(uploaded.getName().lastIndexOf('.') + 1) : null; if ("ZIP".equalsIgnoreCase(fileExtension)) { logger.debug("Decompress zip file"); uploaded = unzipUploadedFile(uploaded); } else if ("GZ".equalsIgnoreCase(fileExtension)) { logger.debug("Decompress gzip file"); uploaded = ungzipUploadedFile(uploaded); } return uploaded; }
Example 3
Source File: PostReceiver.java From android-lite-http with Apache License 2.0 | 6 votes |
/** * 处理表单文件 */ private void processUploadedFile(String filePath, FileItem item, PrintWriter writer) throws Exception { String filename = item.getName(); int index = filename.lastIndexOf("\\"); filename = filename.substring(index + 1, filename.length()); long fileSize = item.getSize(); if (filename.equals("") && fileSize == 0) return; File uploadFile = new File(filePath + "/" + filename); item.write(uploadFile); writer.println( "File Part [" + filename + "] is saved." + " contentType: " + item .getContentType() + " , size: " + fileSize + "\r\n"); System.out.println( "File Part [" + filename + "] is saved." + " contentType: " + item .getContentType() + " , size: " + fileSize); }
Example 4
Source File: UploadDatasetFileAction.java From Knowage-Server with GNU Affero General Public License v3.0 | 6 votes |
private void checkUploadedFile(FileItem uploaded) { logger.debug("IN"); try { // check if the uploaded file is empty if (uploaded.getSize() == 0) { throw new SpagoBIServiceException(getActionName(), "The uploaded file is empty"); } fileExtension = uploaded.getName().lastIndexOf('.') > 0 ? uploaded.getName().substring(uploaded.getName().lastIndexOf('.') + 1) : null; logger.debug("File extension: [" + fileExtension + "]"); // check if the extension is valid (XLS, CSV) if (!"CSV".equalsIgnoreCase(fileExtension) && !"XLS".equalsIgnoreCase(fileExtension)) { throw new SpagoBIServiceException(getActionName(), "The uploaded file has an invalid extension. Choose a CSV or XLS file."); } } finally { logger.debug("OUT"); } }
Example 5
Source File: AdminUserFieldService.java From lutece-core with BSD 3-Clause "New" or "Revised" License | 5 votes |
/** * Check if the user fields are correctly filled * * @param request * HttpServletRequest * @param locale * locale * @return null if there are no problem */ public static String checkUserFields( HttpServletRequest request, Locale locale ) { // Specific attributes List<IAttribute> listAttributes = _attributeService.getAllAttributesWithoutFields( locale ); for ( IAttribute attribute : listAttributes ) { if ( attribute.isAttributeImage( ) ) { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; FileItem fileItem = multipartRequest.getFile( PARAMETER_ATTRIBUTE + CONSTANT_UNDERSCORE + attribute.getIdAttribute( ) ); String strUpdateAttribute = request.getParameter( PARAMETER_UPDATE_ATTRIBUTE + CONSTANT_UNDERSCORE + attribute.getIdAttribute( ) ); if ( attribute.isMandatory( ) && ( strUpdateAttribute != null ) && ( ( fileItem == null ) || ( fileItem.getSize( ) == 0 ) ) ) { return AdminMessageService.getMessageUrl( request, Messages.MANDATORY_FIELDS, AdminMessage.TYPE_STOP ); } } else { String value = request.getParameter( PARAMETER_ATTRIBUTE + CONSTANT_UNDERSCORE + attribute.getIdAttribute( ) ); if ( attribute.isMandatory( ) && ( ( value == null ) || value.equals( CONSTANT_EMPTY_STRING ) ) ) { return AdminMessageService.getMessageUrl( request, Messages.MANDATORY_FIELDS, AdminMessage.TYPE_STOP ); } } } return null; }
Example 6
Source File: SaveArtifactAction.java From Knowage-Server with GNU Affero General Public License v3.0 | 5 votes |
private void checkUploadedFile(FileItem uploaded) { logger.debug("IN"); try { // check if the uploaded file exceeds the maximum dimension int maxSize = GeneralUtilities.getTemplateMaxSize(); if (uploaded.getSize() > maxSize) { throw new SpagoBIEngineServiceException(getActionName(), "The uploaded file exceeds the maximum size, that is " + maxSize); } } finally { logger.debug("OUT"); } }
Example 7
Source File: SaveMetaModelAction.java From Knowage-Server with GNU Affero General Public License v3.0 | 5 votes |
private void checkUploadedFile(FileItem uploaded) { logger.debug("IN"); try { // check if the uploaded file exceeds the maximum dimension int maxSize = GeneralUtilities.getTemplateMaxSize(); if (uploaded.getSize() > maxSize) { throw new SpagoBIEngineServiceException(getActionName(), "The uploaded file exceeds the maximum size, that is " + maxSize); } } finally { logger.debug("OUT"); } }
Example 8
Source File: ClassifyUtils.java From ontopia with Apache License 2.0 | 5 votes |
public static ClassifiableContentIF getFileUploadContent(HttpServletRequest request) { // Handle file upload String contentType = request.getHeader("content-type"); // out.write("CT: " + contentType + " " + tm + " " + id); if (contentType != null && contentType.startsWith("multipart/form-data")) { try { FileUpload upload = new FileUpload(new DefaultFileItemFactory()); for (FileItem item : upload.parseRequest(request)) { if (item.getSize() > 0) { // ISSUE: could make use of content type if known byte[] content = item.get(); ClassifiableContent cc = new ClassifiableContent(); String name = item.getName(); if (name != null) cc.setIdentifier("fileupload:name:" + name); else cc.setIdentifier("fileupload:field:" + item.getFieldName()); cc.setContent(content); return cc; } } } catch (Exception e) { throw new OntopiaRuntimeException(e); } } return null; }
Example 9
Source File: ImportPlaylistController.java From airsonic with GNU General Public License v3.0 | 5 votes |
@PostMapping protected String handlePost(RedirectAttributes redirectAttributes, HttpServletRequest request ) { Map<String, Object> map = new HashMap<String, Object>(); try { if (ServletFileUpload.isMultipartContent(request)) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<?> items = upload.parseRequest(request); for (Object o : items) { FileItem item = (FileItem) o; if ("file".equals(item.getFieldName()) && !StringUtils.isBlank(item.getName())) { if (item.getSize() > MAX_PLAYLIST_SIZE_MB * 1024L * 1024L) { throw new Exception("The playlist file is too large. Max file size is " + MAX_PLAYLIST_SIZE_MB + " MB."); } String playlistName = FilenameUtils.getBaseName(item.getName()); String fileName = FilenameUtils.getName(item.getName()); String username = securityService.getCurrentUsername(request); Playlist playlist = playlistService.importPlaylist(username, playlistName, fileName, item.getInputStream(), null); map.put("playlist", playlist); } } } } catch (Exception e) { map.put("error", e.getMessage()); } redirectAttributes.addFlashAttribute("model", map); return "redirect:importPlaylist"; }
Example 10
Source File: UploadDatasetFileResource.java From Knowage-Server with GNU Affero General Public License v3.0 | 4 votes |
private void checkDatasetFileMaxSizeSystem(FileItem uploaded) { int maxSize = GeneralUtilities.getDataSetFileMaxSize(); if (uploaded.getSize() > maxSize) { throw new SpagoBIServiceException(getActionName(), "The uploaded file exceeds the maximum size, that is " + maxSize + " bytes"); } }
Example 11
Source File: MultipartUtil.java From lutece-core with BSD 3-Clause "New" or "Revised" License | 4 votes |
private static void processItem( FileItem item, String strEncoding, boolean bActivateNormalizeFileName, Map<String, List<FileItem>> mapFiles, Map<String, String [ ]> mapParameters ) { if ( item.isFormField( ) ) { String strValue = StringUtils.EMPTY; if ( item.getSize( ) > 0 ) { try { strValue = item.getString( strEncoding ); } catch( UnsupportedEncodingException ex ) { // if encoding problem, try with system encoding strValue = item.getString( ); } } // check if item of same name already in map String [ ] curParam = mapParameters.get( item.getFieldName( ) ); if ( curParam == null ) { // simple form field mapParameters.put( item.getFieldName( ), new String [ ] { strValue } ); } else { // array of simple form fields String [ ] newArray = new String [ curParam.length + 1]; System.arraycopy( curParam, 0, newArray, 0, curParam.length ); newArray [curParam.length] = strValue; mapParameters.put( item.getFieldName( ), newArray ); } } else { // multipart file field, if the parameter filter ActivateNormalizeFileName is // set to true // all file name will be normalize FileItem fileItem = bActivateNormalizeFileName ? new NormalizeFileItem( item ) : item; List<FileItem> listFileItem = mapFiles.get( fileItem.getFieldName( ) ); if ( listFileItem != null ) { listFileItem.add( fileItem ); } else { listFileItem = new ArrayList<>( 1 ); listFileItem.add( fileItem ); mapFiles.put( fileItem.getFieldName( ), listFileItem ); } } }
Example 12
Source File: UploadImageFileTemporary.java From projectforge-webapp with GNU General Public License v3.0 | 4 votes |
/** * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { log.debug("Start doPost"); final PFUserDO user = UserFilter.getUser(request); if (user == null) { log.warn("Calling of UploadImageFileTemp without logged in user."); return; } // check if the sent request is of the type multi part final boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart == false) { log.warn("The request is not of the type multipart"); return; } try { // Parse the request final FileItem imgFile = getImgFileItem(request); // get the file item of the multipart request // everything ok so far so process the file uploaded if (imgFile == null || imgFile.getSize() == 0) { log.warn("No file was uploaded, aborting!"); return; } if (imgFile.getSize() > MAX_SUPPORTED_FILE_SIZE) { log.warn("Maximum file size exceded for file '" + imgFile.getName() + "': " + imgFile.getSize()); return; } final File tmpImageFile = ImageCropperUtils.getTempFile(user); // Temporary file log.info("Writing tmp file: " + tmpImageFile.getAbsolutePath()); try { // Write new File imgFile.write(tmpImageFile); } catch (Exception e) { log.error("Could not write " + tmpImageFile.getAbsolutePath(), e); } } catch (FileUploadException ex) { log.warn("Failure reading the multipart request"); log.warn(ex.getMessage(), ex); } final ServletOutputStream out = response.getOutputStream(); out.println("text/html"); }
Example 13
Source File: AbstractFileUploadExecutor.java From attic-stratos with Apache License 2.0 | 4 votes |
protected void parseRequest(HttpServletRequest request) throws FileUploadFailedException, FileSizeLimitExceededException { fileItemsMap.set(new HashMap<String, ArrayList<FileItemData>>()); formFieldsMap.set(new HashMap<String, ArrayList<String>>()); ServletRequestContext servletRequestContext = new ServletRequestContext(request); boolean isMultipart = ServletFileUpload.isMultipartContent(servletRequestContext); Long totalFileSize = 0L; if (isMultipart) { List items; try { items = parseRequest(servletRequestContext); } catch (FileUploadException e) { String msg = "File upload failed"; log.error(msg, e); throw new FileUploadFailedException(msg, e); } boolean multiItems = false; if (items.size() > 1) { multiItems = true; } // Add the uploaded items to the corresponding maps. for (Iterator iter = items.iterator(); iter.hasNext();) { FileItem item = (FileItem) iter.next(); String fieldName = item.getFieldName().trim(); if (item.isFormField()) { if (formFieldsMap.get().get(fieldName) == null) { formFieldsMap.get().put(fieldName, new ArrayList<String>()); } try { formFieldsMap.get().get(fieldName).add(new String(item.get(), "UTF-8")); } catch (UnsupportedEncodingException ignore) { } } else { String fileName = item.getName(); if ((fileName == null || fileName.length() == 0) && multiItems) { continue; } if (fileItemsMap.get().get(fieldName) == null) { fileItemsMap.get().put(fieldName, new ArrayList<FileItemData>()); } totalFileSize += item.getSize(); if (totalFileSize < totalFileUploadSizeLimit) { fileItemsMap.get().get(fieldName).add(new FileItemData(item)); } else { throw new FileSizeLimitExceededException(getFileSizeLimit() / 1024 / 1024); } } } } }
Example 14
Source File: FeedbackEntityProvider.java From sakai with Educational Community License v2.0 | 4 votes |
private List<FileItem> getAttachments(final Map<String, Object> params) throws Exception { final List<FileItem> fileItems = new ArrayList<FileItem>(); final String uploadsDone = (String) params.get(RequestFilter.ATTR_UPLOADS_DONE); if (uploadsDone != null && uploadsDone.equals(RequestFilter.ATTR_UPLOADS_DONE)) { log.debug("UPLOAD STATUS: " + params.get("upload.status")); FileItem attachment1 = (FileItem) params.get("attachment_0"); if (attachment1 != null && attachment1.getSize() > 0) { fileItems.add(attachment1); } FileItem attachment2 = (FileItem) params.get("attachment_1"); if (attachment2 != null && attachment2.getSize() > 0) { fileItems.add(attachment2); } FileItem attachment3 = (FileItem) params.get("attachment_2"); if (attachment3 != null && attachment3.getSize() > 0) { fileItems.add(attachment3); } FileItem attachment4 = (FileItem) params.get("attachment_3"); if (attachment4 != null && attachment4.getSize() > 0) { fileItems.add(attachment4); } FileItem attachment5 = (FileItem) params.get("attachment_4"); if (attachment5 != null && attachment5.getSize() > 0) { fileItems.add(attachment5); } } long totalSize = 0L; for (FileItem fileItem : fileItems) { totalSize += fileItem.getSize(); } if (totalSize > maxAttachmentsBytes) { throw new AttachmentsTooBigException(); } return fileItems; }
Example 15
Source File: FileUploadUtils.java From TinyMooc with Apache License 2.0 | 4 votes |
public static final HashMap UploadFile(HttpServletRequest request, HttpServletResponse response, String filepaths) throws Exception { HashMap params = new HashMap(); String pathType = "images"; if (!(filepaths.equals(""))) pathType = filepaths; String readPath = ""; String contextPath = ""; if ((readPath == null) || (readPath.equals(""))) readPath = request.getSession().getServletContext().getRealPath(""); if ((contextPath == null) || (contextPath.equals(""))) contextPath = request.getContextPath(); String savePhotoPath = mkdirFile(readPath, pathType, true); if (ServletFileUpload.isMultipartContent(request)) { DiskFileItemFactory dff = new DiskFileItemFactory(); dff.setSizeThreshold(1024000); ServletFileUpload sfu = new ServletFileUpload(dff); List fileItems = sfu.parseRequest(request); sfu.setFileSizeMax(5000000L); sfu.setSizeMax(10000000L); sfu.setHeaderEncoding("UTF-8"); Iterator iter = fileItems.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { String name = item.getFieldName(); String value = new String(item.getString().getBytes( "ISO8859-1"), "utf-8"); params.put(name, value); } else if ((item.getSize() > 0L) && (item.getName() != null)) { File fullFile = new File(item.getName()); File fileOnServer = new File(savePhotoPath, fullFile.getName()); item.write(fileOnServer); String fileName2 = fileOnServer.getName(); String fileType = fileName2.substring(fileName2 .lastIndexOf(".")); String filepath = savePhotoPath + "/" + new Date().getTime() + fileType; File newFile = new File(filepath); fileOnServer.renameTo(newFile); String returnString = filepath.substring(readPath .length()); params.put(item.getFieldName(), request.getRequestURL().toString().replace(request.getRequestURI(), "") + contextPath + returnString); } } } return params; }
Example 16
Source File: UploadVideoController.java From TinyMooc with Apache License 2.0 | 4 votes |
@RequestMapping("uploadAll.htm") public ModelAndView uploadAll(HttpServletRequest request, HttpServletResponse response) throws Exception { User user = (User) request.getSession().getAttribute("user"); String courseIntro = null, lessonNum = null, courseTitle = null, message = null, courseId = null; if (ServletFileUpload.isMultipartContent(request)) { DiskFileItemFactory disk = new DiskFileItemFactory(); disk.setSizeThreshold(20 * 1024); disk.setRepository(disk.getRepository()); ServletFileUpload up = new ServletFileUpload(disk); int maxsize = 1000 * 1024 * 1024; List list = up.parseRequest(request); Iterator i = list.iterator(); String resourceUrl = ""; String postfix = ""; while (i.hasNext()) { FileItem fm = (FileItem) i.next(); if (!fm.isFormField()) { String filePath = fm.getName(); String fileName = ""; int startIndex = filePath.lastIndexOf("\\"); if (startIndex != -1) { fileName = filePath.substring(startIndex + 1); } else { fileName = filePath; } resourceUrl = fileName; if (fm.getSize() > maxsize) { message = "文件太大,不超过1000M"; break; } String filepath = "D:\\GitHub\\TinyMooc\\src\\main\\webapp\\resource\\video"; postfix = resourceUrl.substring(resourceUrl.lastIndexOf(".") + 1, resourceUrl.length()); File uploadPath = new File(filepath); File saveFile = new File(uploadPath, fileName); fm.write(saveFile); message = "文件上传成功!"; } else { String formName = fm.getFieldName(); String con = fm.getString("utf-8"); if (formName.equals("courseIntro")) { courseIntro = con; } else if (formName.equals("lessonNum")) { lessonNum = con; } else if (formName.equals("courseTitle")) { courseTitle = con; } else if (formName.equals("courseId")) { courseId = con; } } } Course course = new Course(); course.setCourseId(UUIDGenerator.randomUUID()); course.setApplyDate(new Date()); course.setCourse(uploadService.findById(Course.class, courseId)); course.setCourseIntro(courseIntro); course.setCourseState("申请中"); course.setCourseTitle(courseTitle); course.setLessonNum(Integer.parseInt(lessonNum)); course.setScanNum(0); uploadService.save(course); UserCourse uC = new UserCourse(); uC.setCourse(course); uC.setUserCourseId(UUIDGenerator.randomUUID()); uC.setUserPosition("创建者"); uC.setUser(user); uploadService.save(uC); Resource resource = new Resource(); resource.setResourceId(UUIDGenerator.randomUUID()); resource.setResourceObject(course.getCourseId()); resource.setType("video"); uploadService.save(resource); Video video = new Video(); video.setResourceId(resource.getResourceId()); video.setResource(resource); video.setVideoUrl(resourceUrl); uploadService.save(video); return new ModelAndView("redirect:courseDetailPage.htm?courseId=" + courseId); } return new ModelAndView("redirect:courseDetailPage.htm?courseId=" + courseId); }
Example 17
Source File: InputFileUploadRenderer.java From sakai with Educational Community License v2.0 | 4 votes |
/** * Check for errors (both developer errors and user errors) - return a * user-friendly error message describing the error, or null if there are no * errors. */ private static String checkForErrors(FacesContext context, UIComponent component, String clientId, boolean atDecodeTime) { ExternalContext external = context.getExternalContext(); HttpServletRequest request = (HttpServletRequest) external.getRequest(); UIForm form = null; try { form = getForm(component); } catch (IllegalArgumentException e) { // there are more than one nested form - thats not OK! return "DEVELOPER ERROR: The <inputFileUpload> tag must be enclosed in just ONE form. Nested forms confuse the browser."; } if (form == null || !"multipart/form-data".equals(RendererUtil.getAttribute(context, form, "enctype"))) { return "DEVELOPER ERROR: The <inputFileUpload> tag must be enclosed in a <h:form enctype=\"multipart/form-data\"> tag."; } // check tag attributes String directory = (String) RendererUtil.getAttribute(context, component, "directory"); if (directory != null && directory.length() != 0) { // the tag is configured to persist the uploaded files to a directory. // check that the specified directory exists, and is writeable File dir = new File(directory); if (!dir.isDirectory() || !dir.exists()) { return "DEVELOPER ERROR: The directory specified on the <inputFileUpload> tag does not exist or is not writable.\n" + "Check the permissions on directory:\n" + dir; } } FileItem item = getFileItem(context, component); boolean isMultipartRequest = request.getContentType() != null && request.getContentType().startsWith("multipart/form-data"); boolean wasMultipartRequestFullyParsed = request.getParameter(clientId + ID_HIDDEN_ELEMENT) != null; String requestFilterStatus = (String) request.getAttribute("upload.status"); Object requestFilterUploadLimit = request.getAttribute("upload.limit"); Exception requestFilterException = (Exception) request.getAttribute("upload.exception"); boolean wasDecodeAlreadyCalledOnTheRequest = "true".equals(request.getAttribute(clientId + ATTR_REQUEST_DECODED)); if (wasDecodeAlreadyCalledOnTheRequest && !atDecodeTime) { // decode() was already called on the request, and we're now at encode() time - so don't do further error checking // as the FileItem may no longer be valid. return null; } // at this point, if its not a multipart request, it doesn't have a file and there isn't an error. if (!isMultipartRequest) return null; // check for user errors if ("exception".equals(requestFilterStatus)) { return "An error occured while processing the uploaded file. The error was:\n" + requestFilterException; } else if ("size_limit_exceeded".equals(requestFilterStatus)) { // the user tried to upload too large a file return "The upload size limit of " + requestFilterUploadLimit + "MB has been exceeded."; } else if (item == null || item.getName() == null || item.getName().length() == 0) { // The file item will be null if the component was previously not rendered. return null; } else if (item.getSize() == 0) { return "The filename '"+item.getName()+"' is invalid. Please select a valid file."; } if (!wasMultipartRequestFullyParsed) { return "An error occured while processing the uploaded file. The error was:\n" + "DEVELOPER ERROR: The <inputFileUpload> tag requires a <filter> in web.xml to parse the uploaded file.\n" + "Check that the Sakai RequestFilter is properly configured in web.xml."; } if (item.getName().indexOf("..") >= 0) { return "The filename '"+item.getName()+"' is invalid. Please select a valid file."; } // everything checks out fine! The upload was parsed, and a FileItem // exists with a filename and non-zero length return null; }
Example 18
Source File: ImportController.java From sakai with Educational Community License v2.0 | 4 votes |
@PostMapping(value = "/importGroups", consumes = "multipart/form-data") public String showImportGroups(@RequestParam(required=false) String groupUploadedText, Model model, HttpServletRequest req) { log.debug("showImportGroups called with value {}", groupUploadedText); // Variable definition Locale userLocale = sakaiService.getCurrentUserLocale(); Map<String, List<String>> importedGroupMap = new HashMap<String, List<String>>(); String uploadedText = StringUtils.EMPTY; String groupFileUploadedText = StringUtils.EMPTY; //Check the uploaded file and contents. FileItem uploadedFileItem = (FileItem) req.getAttribute("groupUploadFile"); if (uploadedFileItem.getSize() > 0) { try (Scanner scanner = new Scanner(uploadedFileItem.getInputStream(), StandardCharsets.UTF_8.name())) { groupFileUploadedText = scanner.useDelimiter("\\A").next(); } catch (Exception e) { log.error("The file {} provided is not valid.", uploadedFileItem.getName()); } } // Check if both options are blank and return an error message if (StringUtils.isAllBlank(groupUploadedText, groupFileUploadedText)) { return returnImportError(model, "import.error.inputrequired", userLocale); } // Process the submitted texts, combine the uploaded and the file into one String uploadedText = String.format("%s\r\n%s", groupUploadedText, groupFileUploadedText); String[] lineArray = uploadedText.split(BULK_LINE_DELIMITER); for (String line : lineArray) { if (StringUtils.isBlank(line)) { continue; } String[] lineContentArray = line.split(BULK_FIELD_DELIMITER); //Each line must contain a groupTitle and a userEid if (lineContentArray.length == 2) { String groupTitle = StringUtils.trimToNull(lineContentArray[0]); String userEid = StringUtils.trimToNull(lineContentArray[1]); if (StringUtils.isAnyBlank(groupTitle, userEid)) { // One of the items of the line is blank, redirect to the import form again displaying an error. return returnImportError(model, "import.error.wrongformat", userLocale); } if (groupTitle.length() > 99) { // One of the items of the line has more than 99 characters, redirect to the import form again displaying an error. return returnImportError(model, "import.error.titlelength", userLocale); } if (importedGroupMap.get(groupTitle) != null) { // If the map contains an entry for that group, add the user to the list importedGroupMap.get(groupTitle).add(userEid); } else { // If the map does not contain an entry for that group, create a list and add the member to the list List<String> newUserlist = new ArrayList<String>(); newUserlist.add(userEid); importedGroupMap.put(groupTitle, newUserlist); } } else { // One line does not contain two items, redirect to the import form again displaying an error. return returnImportError(model, "import.error.wrongformat", userLocale); } } //Redirect to the confirmation page once the map are correct return showImportConfirmation(model, importedGroupMap); }
Example 19
Source File: UploadHelper.java From smart-framework with Apache License 2.0 | 4 votes |
/** * 创建 multipart 请求参数列表 */ public static List<Object> createMultipartParamList(HttpServletRequest request) throws Exception { // 定义参数列表 List<Object> paramList = new ArrayList<Object>(); // 创建两个对象,分别对应 普通字段 与 文件字段 Map<String, Object> fieldMap = new HashMap<String, Object>(); List<Multipart> multipartList = new ArrayList<Multipart>(); // 获取并遍历表单项 List<FileItem> fileItemList; try { fileItemList = fileUpload.parseRequest(request); } catch (FileUploadBase.FileSizeLimitExceededException e) { // 异常转换(抛出自定义异常) throw new UploadException(e); } for (FileItem fileItem : fileItemList) { // 分两种情况处理表单项 String fieldName = fileItem.getFieldName(); if (fileItem.isFormField()) { // 处理普通字段 String fieldValue = fileItem.getString(FrameworkConstant.UTF_8); fieldMap.put(fieldName, fieldValue); } else { // 处理文件字段 String fileName = FileUtil.getRealFileName(fileItem.getName()); if (StringUtil.isNotEmpty(fileName)) { long fileSize = fileItem.getSize(); String contentType = fileItem.getContentType(); InputStream inputSteam = fileItem.getInputStream(); // 创建 Multipart 对象,并将其添加到 multipartList 中 Multipart multipart = new Multipart(fieldName, fileName, fileSize, contentType, inputSteam); multipartList.add(multipart); } } } // 初始化参数列表 paramList.add(new Params(fieldMap)); paramList.add(new Multiparts(multipartList)); // 返回参数列表 return paramList; }
Example 20
Source File: UploadDatasetFileAction.java From Knowage-Server with GNU Affero General Public License v3.0 | 2 votes |
private void checkDatasetFileMaxSize(FileItem uploaded, UserProfile userProfile) { logger.debug("Method checkDatasetFileMaxSize(): Start"); // first check that the user profile isn't null if (userProfile == null) { throw new SpagoBIServiceException(getActionName(), "Impossible to check [ " + DATASET_FILE_MAX_SIZE + "] attribute without a valide user profile"); } try { if (userProfile.getUserAttributes().containsKey(DATASET_FILE_MAX_SIZE)) { // the user profile contains the attribute that defines dataset file max size logger.debug("Method checkDatasetFileMaxSize(): Attribute [ " + DATASET_FILE_MAX_SIZE + " ] defined for [" + userProfile.getUserName() + " ] profile. Validation needed"); String datasetFileMaxSizeStr = (String) userProfile.getUserAttribute(DATASET_FILE_MAX_SIZE); if (!datasetFileMaxSizeStr.equals("")) { long datasetFileMaxSize = Long.parseLong(datasetFileMaxSizeStr); if (uploaded.getSize() > datasetFileMaxSize) { throw new SpagoBIServiceException(getActionName(), "The uploaded file exceeds the maximum size assigned to the user, that is " + datasetFileMaxSize + " bytes"); } } else { checkDatasetFileMaxSizeSystem(uploaded); } } else { logger.debug("Method checkDatasetFileMaxSize(): Attribute [ " + DATASET_FILE_MAX_SIZE + " ] not defined for [" + userProfile.getUserName() + " ] profile. Check default system max dimension"); // check if the uploaded file exceeds the maximum default dimension checkDatasetFileMaxSizeSystem(uploaded); } logger.debug("Method checkDatasetFileMaxSize(): End"); } catch (Throwable t) { logger.error("Error retrieving user attribute [ " + DATASET_FILE_MAX_SIZE + " ] " + t); throw new SpagoBIServiceException(getActionName(), "The uploaded file exceeds the maximum size", t); } }