Java Code Examples for org.apache.commons.fileupload.FileItem#getString()
The following examples show how to use
org.apache.commons.fileupload.FileItem#getString() .
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: AdapterHTTP.java From Knowage-Server with GNU Affero General Public License v3.0 | 6 votes |
private void handleMultipartForm(HttpServletRequest request, RequestContextIFace requestContext) throws Exception{ SourceBean serviceRequest = requestContext.getServiceRequest(); // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request List fileItems = upload.parseRequest(request); Iterator iter = fileItems.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { String name = item.getFieldName(); String value = item.getString(); serviceRequest.setAttribute(name, value); } else { processFileField(item, requestContext); } } }
Example 2
Source File: AdapterPortlet.java From Knowage-Server with GNU Affero General Public License v3.0 | 6 votes |
private void handleMultipartForm(ActionRequest request, RequestContextIFace requestContext) throws Exception { SourceBean serviceRequest = requestContext.getServiceRequest(); // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler PortletFileUpload upload = new PortletFileUpload(factory); // Parse the request List fileItems = upload.parseRequest(request); Iterator iter = fileItems.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { String name = item.getFieldName(); String value = item.getString(); serviceRequest.setAttribute(name, value); } else { processFileField(item, requestContext); } } }
Example 3
Source File: AdapterHTTP.java From Knowage-Server with GNU Affero General Public License v3.0 | 6 votes |
/** * Handle multipart form. * * @param request the request * @param requestContext the request context * * @throws Exception the exception */ private void handleMultipartForm(HttpServletRequest request, RequestContextIFace requestContext) throws Exception { SourceBean serviceRequest = requestContext.getServiceRequest(); // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request List fileItems = upload.parseRequest(request); Iterator iter = fileItems.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { String name = item.getFieldName(); String value = item.getString(request.getCharacterEncoding()); serviceRequest.setAttribute(name, value); } else { processFileField(item, requestContext); } } }
Example 4
Source File: AdapterPortlet.java From Knowage-Server with GNU Affero General Public License v3.0 | 6 votes |
/** * Handle multipart form. * * @param request the request * @param requestContext the request context * * @throws Exception the exception */ private void handleMultipartForm(ActionRequest request, RequestContextIFace requestContext) throws Exception { SourceBean serviceRequest = requestContext.getServiceRequest(); // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler PortletFileUpload upload = new PortletFileUpload(factory); // Parse the request List fileItems = upload.parseRequest(request); Iterator iter = fileItems.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { String name = item.getFieldName(); String value = item.getString(); serviceRequest.setAttribute(name, value); } else { processFileField(item, requestContext); } } }
Example 5
Source File: AdapterHTTP.java From Knowage-Server with GNU Affero General Public License v3.0 | 6 votes |
/** * Handle multipart form. * * @param request the request * @param requestContext the request context * * @throws Exception the exception */ private void handleMultipartForm(HttpServletRequest request, RequestContextIFace requestContext) throws Exception { SourceBean serviceRequest = requestContext.getServiceRequest(); // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request List fileItems = upload.parseRequest(request); Iterator iter = fileItems.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { String name = item.getFieldName(); String value = item.getString(request.getCharacterEncoding()); serviceRequest.setAttribute(name, value); } else { processFileField(item, requestContext); } } }
Example 6
Source File: UploadDatasetFileResource.java From Knowage-Server with GNU Affero General Public License v3.0 | 6 votes |
private FileItem handleMultipartForm(HttpServletRequest request) throws Exception { // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request List fileItems = upload.parseRequest(request); Iterator iter = fileItems.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { String name = item.getFieldName(); String value = item.getString(); } else { return item; } } return null; }
Example 7
Source File: StandardMultipartResolver.java From AndServer with Apache License 2.0 | 5 votes |
/** * Parse the given List of Commons FileItems into a MultipartParsingResult, containing MultipartFile instances and a * Map of multipart parameter. * * @param fileItems the Commons FileItems to parse. * @param encoding the encoding to use for form fields. * * @return the MultipartParsingResult. * * @see StandardMultipartFile#StandardMultipartFile(FileItem) */ protected MultipartParsingResult parseFileItems(List<FileItem> fileItems, String encoding) { MultiValueMap<String, MultipartFile> multipartFiles = new LinkedMultiValueMap<>(); MultiValueMap<String, String> multipartParameters = new LinkedMultiValueMap<>(); Map<String, String> multipartContentTypes = new HashMap<>(); // Extract multipart files and multipart parameters. for (FileItem fileItem : fileItems) { if (fileItem.isFormField()) { String value; String partEncoding = determineEncoding(fileItem.getContentType(), encoding); if (partEncoding != null) { try { value = fileItem.getString(partEncoding); } catch (UnsupportedEncodingException ex) { value = fileItem.getString(); } } else { value = fileItem.getString(); } List<String> curParam = multipartParameters.get(fileItem.getFieldName()); if (curParam == null) { // Simple form field. curParam = new LinkedList<>(); curParam.add(value); multipartParameters.put(fileItem.getFieldName(), curParam); } else { // Array of simple form fields. curParam.add(value); } multipartContentTypes.put(fileItem.getFieldName(), fileItem.getContentType()); } else { StandardMultipartFile file = createMultipartFile(fileItem); multipartFiles.add(file.getName(), file); } } return new MultipartParsingResult(multipartFiles, multipartParameters, multipartContentTypes); }
Example 8
Source File: AdapterHTTP.java From Knowage-Server with GNU Affero General Public License v3.0 | 5 votes |
private void handleMultipartForm(HttpServletRequest request, RequestContextIFace requestContext) throws Exception { SourceBean serviceRequest = requestContext.getServiceRequest(); // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // This is done to make upload work in Unix solaris // ((DiskFileItemFactory)factory).setSizeThreshold(5242880); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // upload.setFileSizeMax(5242880); // upload.setSizeMax(5242880); // Parse the request List fileItems = upload.parseRequest(request); Iterator iter = fileItems.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { String name = item.getFieldName(); String value = item.getString(request.getCharacterEncoding()); serviceRequest.setAttribute(name, value); } else { processFileField(item, requestContext); } } }
Example 9
Source File: FessMultipartRequestHandler.java From fess with Apache License 2.0 | 5 votes |
protected void addTextParameter(final HttpServletRequest request, final FileItem item) { final String name = item.getFieldName(); final String encoding = request.getCharacterEncoding(); String value = null; boolean haveValue = false; if (encoding != null) { try { value = item.getString(encoding); haveValue = true; } catch (final Exception e) {} } if (!haveValue) { try { value = item.getString("ISO-8859-1"); } catch (final java.io.UnsupportedEncodingException uee) { value = item.getString(); } haveValue = true; } if (request instanceof MultipartRequestWrapper) { final MultipartRequestWrapper wrapper = (MultipartRequestWrapper) request; wrapper.setParameter(name, value); } final String[] oldArray = elementsText.get(name); final String[] newArray; if (oldArray != null) { newArray = new String[oldArray.length + 1]; System.arraycopy(oldArray, 0, newArray, 0, oldArray.length); newArray[oldArray.length] = value; } else { newArray = new String[] { value }; } elementsText.put(name, newArray); elementsAll.put(name, newArray); }
Example 10
Source File: UploadHandleServlet.java From rainbow with Apache License 2.0 | 5 votes |
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("UTF-8"); if (!ServletFileUpload.isMultipartContent(request)) { return; } this.fileList = upload.parseRequest(request); // System.out.println(fileList.size()); for (FileItem item : fileList) { if (item.isFormField()) { String value = item.getString("UTF-8"); // System.out.print(value); names.add(value); } else { String filename = item.getName(); if (filename == null) continue; File newFile = new File(filename); // System.out.println(newFile.getCanonicalPath()); // item.write(newFile); this.names.add(newFile.getAbsolutePath().toString()); saveFile(item); } } } catch (Exception e) { e.printStackTrace(); } }
Example 11
Source File: CommonsFileUploadSupport.java From spring4-understanding with Apache License 2.0 | 4 votes |
/** * Parse the given List of Commons FileItems into a Spring MultipartParsingResult, * containing Spring MultipartFile instances and a Map of multipart parameter. * @param fileItems the Commons FileIterms to parse * @param encoding the encoding to use for form fields * @return the Spring MultipartParsingResult * @see CommonsMultipartFile#CommonsMultipartFile(org.apache.commons.fileupload.FileItem) */ protected MultipartParsingResult parseFileItems(List<FileItem> fileItems, String encoding) { MultiValueMap<String, MultipartFile> multipartFiles = new LinkedMultiValueMap<String, MultipartFile>(); Map<String, String[]> multipartParameters = new HashMap<String, String[]>(); Map<String, String> multipartParameterContentTypes = new HashMap<String, String>(); // Extract multipart files and multipart parameters. for (FileItem fileItem : fileItems) { if (fileItem.isFormField()) { String value; String partEncoding = determineEncoding(fileItem.getContentType(), encoding); if (partEncoding != null) { try { value = fileItem.getString(partEncoding); } catch (UnsupportedEncodingException ex) { if (logger.isWarnEnabled()) { logger.warn("Could not decode multipart item '" + fileItem.getFieldName() + "' with encoding '" + partEncoding + "': using platform default"); } value = fileItem.getString(); } } else { value = fileItem.getString(); } String[] curParam = multipartParameters.get(fileItem.getFieldName()); if (curParam == null) { // simple form field multipartParameters.put(fileItem.getFieldName(), new String[] {value}); } else { // array of simple form fields String[] newParam = StringUtils.addStringToArray(curParam, value); multipartParameters.put(fileItem.getFieldName(), newParam); } multipartParameterContentTypes.put(fileItem.getFieldName(), fileItem.getContentType()); } else { // multipart file field CommonsMultipartFile file = new CommonsMultipartFile(fileItem); multipartFiles.add(file.getName(), file); if (logger.isDebugEnabled()) { logger.debug("Found multipart file [" + file.getName() + "] of size " + file.getSize() + " bytes with original filename [" + file.getOriginalFilename() + "], stored " + file.getStorageDescription()); } } } return new MultipartParsingResult(multipartFiles, multipartParameters, multipartParameterContentTypes); }
Example 12
Source File: CommonsFileUploadSupport.java From spring-analysis-note with MIT License | 4 votes |
/** * Parse the given List of Commons FileItems into a Spring MultipartParsingResult, * containing Spring MultipartFile instances and a Map of multipart parameter. * @param fileItems the Commons FileItems to parse * @param encoding the encoding to use for form fields * @return the Spring MultipartParsingResult * @see CommonsMultipartFile#CommonsMultipartFile(org.apache.commons.fileupload.FileItem) */ protected MultipartParsingResult parseFileItems(List<FileItem> fileItems, String encoding) { MultiValueMap<String, MultipartFile> multipartFiles = new LinkedMultiValueMap<>(); Map<String, String[]> multipartParameters = new HashMap<>(); Map<String, String> multipartParameterContentTypes = new HashMap<>(); // Extract multipart files and multipart parameters. for (FileItem fileItem : fileItems) { if (fileItem.isFormField()) { String value; String partEncoding = determineEncoding(fileItem.getContentType(), encoding); try { value = fileItem.getString(partEncoding); } catch (UnsupportedEncodingException ex) { if (logger.isWarnEnabled()) { logger.warn("Could not decode multipart item '" + fileItem.getFieldName() + "' with encoding '" + partEncoding + "': using platform default"); } value = fileItem.getString(); } String[] curParam = multipartParameters.get(fileItem.getFieldName()); if (curParam == null) { // simple form field multipartParameters.put(fileItem.getFieldName(), new String[] {value}); } else { // array of simple form fields String[] newParam = StringUtils.addStringToArray(curParam, value); multipartParameters.put(fileItem.getFieldName(), newParam); } multipartParameterContentTypes.put(fileItem.getFieldName(), fileItem.getContentType()); } else { // multipart file field CommonsMultipartFile file = createMultipartFile(fileItem); multipartFiles.add(file.getName(), file); LogFormatUtils.traceDebug(logger, traceOn -> "Part '" + file.getName() + "', size " + file.getSize() + " bytes, filename='" + file.getOriginalFilename() + "'" + (traceOn ? ", storage=" + file.getStorageDescription() : "") ); } } return new MultipartParsingResult(multipartFiles, multipartParameters, multipartParameterContentTypes); }
Example 13
Source File: UploadUtils.java From Shop-for-JavaWeb with MIT License | 4 votes |
/** * 处理上传内容 * * @param request * @param maxSize * @return */ // @SuppressWarnings("unchecked") private Map<String, Object> initFields(HttpServletRequest request) { // 存储表单字段和非表单字段 Map<String, Object> map = new HashMap<String, Object>(); // 第一步:判断request boolean isMultipart = ServletFileUpload.isMultipartContent(request); // 第二步:解析request if (isMultipart) { // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // 阀值,超过这个值才会写到临时目录,否则在内存中 factory.setSizeThreshold(1024 * 1024 * 10); factory.setRepository(new File(tempPath)); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("UTF-8"); // 最大上传限制 upload.setSizeMax(maxSize); /* FileItem */ List<FileItem> items = null; // Parse the request try { items = upload.parseRequest(request); } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } // 第3步:处理uploaded items if (items != null && items.size() > 0) { Iterator<FileItem> iter = items.iterator(); // 文件域对象 List<FileItem> list = new ArrayList<FileItem>(); // 表单字段 Map<String, String> fields = new HashMap<String, String>(); while (iter.hasNext()) { FileItem item = iter.next(); // 处理所有表单元素和文件域表单元素 if (item.isFormField()) { // 表单元素 String name = item.getFieldName(); String value = item.getString(); fields.put(name, value); } else { // 文件域表单元素 list.add(item); } } map.put(FORM_FIELDS, fields); map.put(FILE_FIELDS, list); } } return map; }
Example 14
Source File: AttachmentServlet.java From incubator-retired-wave with Apache License 2.0 | 4 votes |
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Process only multipart requests. if (ServletFileUpload.isMultipartContent(request)) { // Create a factory for disk-based file items. FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler. ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request. try { @SuppressWarnings("unchecked") List<FileItem> items = upload.parseRequest(request); AttachmentId id = null; String waveRefStr = null; FileItem fileItem = null; for (FileItem item : items) { // Process only file upload - discard other form item types. if (item.isFormField()) { if (item.getFieldName().equals("attachmentId")) { id = AttachmentId.deserialise(item.getString()); } if (item.getFieldName().equals("waveRef")) { waveRefStr = item.getString(); } } else { fileItem = item; } } if (id == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No attachment Id in the request."); return; } if (waveRefStr == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No wave reference in request."); return; } WaveletName waveletName = AttachmentUtil.waveRef2WaveletName(waveRefStr); ParticipantId user = sessionManager.getLoggedInUser(request.getSession(false)); boolean isAuthorized = waveletProvider.checkAccessPermission(waveletName, user); if (!isAuthorized) { response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } // Get only the file name not whole path. if (fileItem != null && fileItem.getName() != null) { String fileName = FilenameUtils.getName(fileItem.getName()); service.storeAttachment(id, fileItem.getInputStream(), waveletName, fileName, user); response.setStatus(HttpServletResponse.SC_CREATED); String msg = String.format("The file with name: %s and id: %s was created successfully.", fileName, id); LOG.fine(msg); response.getWriter().print("OK"); response.flushBuffer(); } } catch (Exception e) { LOG.severe("Upload error", e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An error occurred while upload the file : " + e.getMessage()); } } else { LOG.severe("Request contents type is not supported by the servlet."); response.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, "Request contents type is not supported by the servlet."); } }
Example 15
Source File: CommonsFileUploadSupport.java From lams with GNU General Public License v2.0 | 4 votes |
/** * Parse the given List of Commons FileItems into a Spring MultipartParsingResult, * containing Spring MultipartFile instances and a Map of multipart parameter. * @param fileItems the Commons FileIterms to parse * @param encoding the encoding to use for form fields * @return the Spring MultipartParsingResult * @see CommonsMultipartFile#CommonsMultipartFile(org.apache.commons.fileupload.FileItem) */ protected MultipartParsingResult parseFileItems(List<FileItem> fileItems, String encoding) { MultiValueMap<String, MultipartFile> multipartFiles = new LinkedMultiValueMap<String, MultipartFile>(); Map<String, String[]> multipartParameters = new HashMap<String, String[]>(); Map<String, String> multipartParameterContentTypes = new HashMap<String, String>(); // Extract multipart files and multipart parameters. for (FileItem fileItem : fileItems) { if (fileItem.isFormField()) { String value; String partEncoding = determineEncoding(fileItem.getContentType(), encoding); if (partEncoding != null) { try { value = fileItem.getString(partEncoding); } catch (UnsupportedEncodingException ex) { if (logger.isWarnEnabled()) { logger.warn("Could not decode multipart item '" + fileItem.getFieldName() + "' with encoding '" + partEncoding + "': using platform default"); } value = fileItem.getString(); } } else { value = fileItem.getString(); } String[] curParam = multipartParameters.get(fileItem.getFieldName()); if (curParam == null) { // simple form field multipartParameters.put(fileItem.getFieldName(), new String[] {value}); } else { // array of simple form fields String[] newParam = StringUtils.addStringToArray(curParam, value); multipartParameters.put(fileItem.getFieldName(), newParam); } multipartParameterContentTypes.put(fileItem.getFieldName(), fileItem.getContentType()); } else { // multipart file field CommonsMultipartFile file = createMultipartFile(fileItem); multipartFiles.add(file.getName(), file); if (logger.isDebugEnabled()) { logger.debug("Found multipart file [" + file.getName() + "] of size " + file.getSize() + " bytes with original filename [" + file.getOriginalFilename() + "], stored " + file.getStorageDescription()); } } } return new MultipartParsingResult(multipartFiles, multipartParameters, multipartParameterContentTypes); }
Example 16
Source File: ExtendedMultiPartRequestHandler.java From jivejdon with Apache License 2.0 | 4 votes |
/** * Adds a regular text parameter to the set of text parameters for this * request and also to the list of all parameters. Handles the case of * multiple values for the same parameter by using an array for the * parameter value. * * @param request * The request in which the parameter was specified. * @param item * The file item for the parameter to add. */ protected void addTextParameter(HttpServletRequest request, FileItem item) { String name = item.getFieldName(); String value = null; boolean haveValue = false; String encoding = request.getCharacterEncoding(); if (encoding != null) { try { value = item.getString(encoding); haveValue = true; } catch (Exception e) { // Handled below, since haveValue is false. } } if (!haveValue) { try { value = item.getString("ISO-8859-1"); } catch (java.io.UnsupportedEncodingException uee) { value = item.getString(); } haveValue = true; } if (request instanceof MultipartRequestWrapper) { MultipartRequestWrapper wrapper = (MultipartRequestWrapper) request; wrapper.setParameter(name, value); } String[] oldArray = (String[]) elementsText.get(name); String[] newArray; if (oldArray != null) { newArray = new String[oldArray.length + 1]; System.arraycopy(oldArray, 0, newArray, 0, oldArray.length); newArray[oldArray.length] = value; } else { newArray = new String[] { value }; } elementsText.put(name, newArray); elementsAll.put(name, newArray); }
Example 17
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 18
Source File: MultiCommonsMultipartResolver.java From sakai with Educational Community License v2.0 | 4 votes |
@Override protected MultipartParsingResult parseFileItems(List<FileItem> fileItems, String encoding) { MultiValueMap<String, MultipartFile> multipartFiles = new LinkedMultiValueMap<String, MultipartFile>(); Map<String, String[]> multipartParameters = new HashMap<String, String[]>(); Map<String, String> multipartParameterContentTypes = new HashMap<String, String>(); // Extract multipart files and multipart parameters. for (FileItem fileItem : fileItems) { if (fileItem.isFormField()) { String value; String partEncoding = determineEncoding(fileItem.getContentType(), encoding); if (partEncoding != null) { try { value = fileItem.getString(partEncoding); } catch (UnsupportedEncodingException ex) { if (log.isWarnEnabled()) { log.warn("Could not decode multipart item '" + fileItem.getFieldName() + "' with encoding '" + partEncoding + "': using platform default"); } value = fileItem.getString(); } } else { value = fileItem.getString(); } String[] curParam = multipartParameters.get(fileItem.getFieldName()); if (curParam == null) { // simple form field multipartParameters.put(fileItem.getFieldName(), new String[] {value}); } else { // array of simple form fields String[] newParam = StringUtils.addStringToArray(curParam, value); multipartParameters.put(fileItem.getFieldName(), newParam); } multipartParameterContentTypes.put(fileItem.getFieldName(), fileItem.getContentType()); } else { // multipart file field CommonsMultipartFile file = new CommonsMultipartFile(fileItem); multipartFiles.add(fileItem.getName(), file); if (log.isDebugEnabled()) { log.debug("Found multipart file [" + file.getName() + "] of size " + file.getSize() + " bytes with original filename [" + file.getOriginalFilename() + "], stored " + file.getStorageDescription()); } } } return new MultipartParsingResult(multipartFiles, multipartParameters, multipartParameterContentTypes); }
Example 19
Source File: CommonsFileUploadSupport.java From java-technology-stack with MIT License | 4 votes |
/** * Parse the given List of Commons FileItems into a Spring MultipartParsingResult, * containing Spring MultipartFile instances and a Map of multipart parameter. * @param fileItems the Commons FileItems to parse * @param encoding the encoding to use for form fields * @return the Spring MultipartParsingResult * @see CommonsMultipartFile#CommonsMultipartFile(org.apache.commons.fileupload.FileItem) */ protected MultipartParsingResult parseFileItems(List<FileItem> fileItems, String encoding) { MultiValueMap<String, MultipartFile> multipartFiles = new LinkedMultiValueMap<>(); Map<String, String[]> multipartParameters = new HashMap<>(); Map<String, String> multipartParameterContentTypes = new HashMap<>(); // Extract multipart files and multipart parameters. for (FileItem fileItem : fileItems) { if (fileItem.isFormField()) { String value; String partEncoding = determineEncoding(fileItem.getContentType(), encoding); try { value = fileItem.getString(partEncoding); } catch (UnsupportedEncodingException ex) { if (logger.isWarnEnabled()) { logger.warn("Could not decode multipart item '" + fileItem.getFieldName() + "' with encoding '" + partEncoding + "': using platform default"); } value = fileItem.getString(); } String[] curParam = multipartParameters.get(fileItem.getFieldName()); if (curParam == null) { // simple form field multipartParameters.put(fileItem.getFieldName(), new String[] {value}); } else { // array of simple form fields String[] newParam = StringUtils.addStringToArray(curParam, value); multipartParameters.put(fileItem.getFieldName(), newParam); } multipartParameterContentTypes.put(fileItem.getFieldName(), fileItem.getContentType()); } else { // multipart file field CommonsMultipartFile file = createMultipartFile(fileItem); multipartFiles.add(file.getName(), file); LogFormatUtils.traceDebug(logger, traceOn -> "Part '" + file.getName() + "', size " + file.getSize() + " bytes, filename='" + file.getOriginalFilename() + "'" + (traceOn ? ", storage=" + file.getStorageDescription() : "") ); } } return new MultipartParsingResult(multipartFiles, multipartParameters, multipartParameterContentTypes); }
Example 20
Source File: UploadUtils.java From jeewx with Apache License 2.0 | 4 votes |
/** * 处理上传内容 * * @param request * @param maxSize * @return */ @SuppressWarnings("unchecked") private Map<String, Object> initFields(HttpServletRequest request) { // 存储表单字段和非表单字段 Map<String, Object> map = new HashMap<String, Object>(); // 第一步:判断request boolean isMultipart = ServletFileUpload.isMultipartContent(request); // 第二步:解析request if (isMultipart) { // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // 阀值,超过这个值才会写到临时目录,否则在内存中 factory.setSizeThreshold(1024 * 1024 * 10); factory.setRepository(new File(tempPath)); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("UTF-8"); // 最大上传限制 upload.setSizeMax(maxSize); /* FileItem */ List<FileItem> items = null; // Parse the request try { items = upload.parseRequest(request); } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } // 第3步:处理uploaded items if (items != null && items.size() > 0) { Iterator<FileItem> iter = items.iterator(); // 文件域对象 List<FileItem> list = new ArrayList<FileItem>(); // 表单字段 Map<String, String> fields = new HashMap<String, String>(); while (iter.hasNext()) { FileItem item = iter.next(); // 处理所有表单元素和文件域表单元素 if (item.isFormField()) { // 表单元素 String name = item.getFieldName(); String value = item.getString(); fields.put(name, value); } else { // 文件域表单元素 list.add(item); } } map.put(FORM_FIELDS, fields); map.put(FILE_FIELDS, list); } } return map; }