Java Code Examples for org.apache.commons.fileupload.FileItem#isFormField()
The following examples show how to use
org.apache.commons.fileupload.FileItem#isFormField() .
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: AnalysisPreviewFile.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 2
Source File: Multipart_mysql.java From openrasp-testcases with MIT License | 6 votes |
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { String id = null; if (req.getMethod().equals("POST")) { if (ServletFileUpload.isMultipartContent(req)) { DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(req); for (FileItem item : items) { if (item.isFormField() && item.getFieldName().equals("id")) { id = item.getString(); break; } } } } if (id == null) { id = "1"; } String result = Mysql.runQuery(id); resp.getWriter().println(result); } catch (Exception e) { resp.getWriter().println(e); } }
Example 3
Source File: UploadServlet.java From Android-Basics-Codes with Artistic License 2.0 | 5 votes |
/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // �ж��ϴ����Ƿ�����ļ� boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { // ��ȡ·�� String realpath = request.getSession().getServletContext().getRealPath("/files"); System.out.println(realpath); File dir = new File(realpath); if (!dir.exists()) dir.mkdirs(); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("UTF-8"); try { // ����������� ��ʵ���� form����ÿ��input�ڵ� List<FileItem> items = upload.parseRequest(request); for (FileItem item : items) { if (item.isFormField()) { // ����DZ� ����ÿ���� ��ӡ������̨ String name1 = item.getFieldName();// �õ�������������� String value = item.getString("UTF-8");// �õ�����ֵ System.out.println(name1 + "=" + value); } else { // ���ļ�д����ǰservlet����Ӧ��·�� item.write(new File(dir, System.currentTimeMillis() + item.getName().substring(item.getName().lastIndexOf(".")))); } } } catch (Exception e) { e.printStackTrace(); } } }
Example 4
Source File: ImpDocXML.java From openprodoc with GNU Affero General Public License v3.0 | 5 votes |
/** * * @param Req * @throws Exception */ @Override protected void ProcessPage(HttpServletRequest Req, PrintWriter out) throws Exception { String FileName=null; InputStream FileData=null; try { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1000000); ServletFileUpload upload = new ServletFileUpload(factory); boolean isMultipart = ServletFileUpload.isMultipartContent(Req); List items = upload.parseRequest(Req); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { FileName=item.getName(); FileData=item.getInputStream(); } } String CurrFold=getActFolderId(Req); DriverGeneric PDSession=SParent.getSessOPD(Req); int Tot=PDSession.ProcessXMLB64(FileData, CurrFold); FileData.close(); out.println(UpFileStatus.SetResultOk(Req, "Total="+Tot)); } catch (Exception e) { out.println(UpFileStatus.SetResultKo(Req, e.getLocalizedMessage())); throw e; } }
Example 5
Source File: HelloController.java From java_study with Apache License 2.0 | 5 votes |
@RequestMapping("/upload") public String uploadFile(HttpServletRequest request) throws Exception { System.out.println("文件上传.."); // 获取到需要上传文件的路径 String realPath = request.getSession().getServletContext().getRealPath("/uploads/"); // 获取file路径,向路径上传文件 File file = new File(realPath); // 判断路径是否存在 if (!file.exists()) { file.mkdirs(); } // 创建磁盘文件工厂方法 DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload fileUpload = new ServletFileUpload(factory); // 解析request对象 List<FileItem> list = fileUpload.parseRequest(request); // 遍历 for (FileItem item : list) { // 判断是普通字段还是文件上传 if (item.isFormField()) { } else { // 获取到上传文件的名称 String fileName = item.getName(); String uuid = UUID.randomUUID().toString().replace("-",""); fileName = uuid + "_" + fileName; // 上传文件 item.write(new File(file, fileName)); // 删除临时文件 item.delete(); } } return "success"; }
Example 6
Source File: AvatarUploadController.java From subsonic with GNU General Public License v3.0 | 5 votes |
@Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { String username = securityService.getCurrentUsername(request); // Check that we have a file upload request. if (!ServletFileUpload.isMultipartContent(request)) { throw new Exception("Illegal request."); } Map<String, Object> map = new HashMap<String, Object>(); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<?> items = upload.parseRequest(request); // Look for file items. for (Object o : items) { FileItem item = (FileItem) o; if (!item.isFormField()) { String fileName = item.getName(); byte[] data = item.get(); if (StringUtils.isNotBlank(fileName) && data.length > 0) { createAvatar(fileName, data, username, map); } else { map.put("error", new Exception("Missing file.")); LOG.warn("Failed to upload personal image. No file specified."); } break; } } map.put("username", username); map.put("avatar", settingsService.getCustomAvatar(username)); ModelAndView result = super.handleRequestInternal(request, response); result.addObject("model", map); return result; }
Example 7
Source File: ArchiveServlet.java From steady with Apache License 2.0 | 4 votes |
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Prepare file upload // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Configure a repository (to ensure a secure temp location is used) ServletContext servletContext = this.getServletConfig().getServletContext(); File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir"); factory.setRepository(repository); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = null; try { // Parse the request items = upload.parseRequest(request); FileItem item = null; ArchivePrinter printer = null; // Process the uploaded items Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { item = iter.next(); // Print the entries of an uploaded ZIP if (!item.isFormField()) { printer = new ArchivePrinter(item.getInputStream()); printer.printEntries(new PrintStream(response.getOutputStream())); } else { //ArchiveServlet.log.info("Parameter [" + item.getFieldName() + "], value [" + item.getString() + "]"); if(item.getFieldName().equals("note")) this.saveNote(item.getString()); } } } catch (FileUploadException e) { //ArchiveServlet.log.error("Error uploading file: " + e.getMessage(), e); } }
Example 8
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 9
Source File: ModDocF.java From openprodoc with GNU Affero General Public License v3.0 | 4 votes |
/** * * @param Req * @throws Exception */ @Override protected void ProcessPage(HttpServletRequest Req, PrintWriter out) throws Exception { String FileName=null; InputStream FileData=null; HashMap <String, String>ListFields=new HashMap(); try { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1000000); ServletFileUpload upload = new ServletFileUpload(factory); boolean isMultipart = ServletFileUpload.isMultipartContent(Req); List items = upload.parseRequest(Req); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) ListFields.put(item.getFieldName(), item.getString()); else { FileName=item.getName(); FileData=item.getInputStream(); } } if (!isMultipart || FileData==null) { out.println("KO"); } else { ListFields=GetDat(Req); PDDocs Doc; DriverGeneric PDSession = getSessOPD(Req); String DType=(String) ListFields.get(PDDocs.fDOCTYPE); if (DType==null) Doc = new PDDocs(PDSession); else Doc = new PDDocs(PDSession, DType); Doc.LoadFull((String) ListFields.get(PDDocs.fPDID)); Record Rec=Doc.getRecSum(); Rec.initList(); Attribute Attr=Rec.nextAttr(); while (Attr!=null) { if (!List.contains(Attr.getName())) { String Val=(String) ListFields.get(Attr.getName()); if (Attr.getType()==Attribute.tBOOLEAN) { if(Val == null || Val.length()==0 || Val.equals("0")) Attr.setValue(false); else Attr.setValue(true); } else if(Val != null) { SParent.FillAttr(Req, Attr, Val, false); } } Attr=Rec.nextAttr(); } Doc.assignValues(Rec); Doc.setParentId(ListFields.get("CurrFold")); Doc.setName(FileName); PDMimeType mt=new PDMimeType(PDSession); Doc.setMimeType(mt.SolveName(FileName)); Doc.setStream(FileData); Doc.update(); out.println(UpFileStatus.SetResultOk(Req, "")); } } catch (Exception e) { out.println(UpFileStatus.SetResultKo(Req, e.getLocalizedMessage())); throw e; } finally { out.close(); } }
Example 10
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; }
Example 11
Source File: UploadRequestWrapper.java From java-tutorial with Creative Commons Attribution Share Alike 4.0 International | 4 votes |
@SuppressWarnings("all") public UploadRequestWrapper(HttpServletRequest request) { super(request); // 判断是否为上传文件 multipart = request.getHeader(MULTIPART_HEADER) != null && request.getHeader(MULTIPART_HEADER).startsWith("multipart/form-data"); if (multipart) { try { // 使用apache的工具解析 DiskFileUpload upload = new DiskFileUpload(); upload.setHeaderEncoding("utf8"); // 解析,获得所有的文本域与文件域 List<FileItem> fileItems = upload.parseRequest(request); for (Iterator<FileItem> it = fileItems.iterator(); it.hasNext(); ) { // 遍历 FileItem item = it.next(); if (item.isFormField()) { // 如果是文本域,直接放到map里 params.put(item.getFieldName(), item.getString("utf8")); } else { // 否则,为文件,先获取文件名称 String filename = item.getName().replace("\\", "/"); filename = filename.substring(filename.lastIndexOf("/") + 1); // 保存到系统临时文件夹中 File file = new File(System.getProperty("java.io.tmpdir"), filename); // 保存文件内容 OutputStream ous = new FileOutputStream(file); ous.write(item.get()); ous.close(); // 放到map中 params.put(item.getFieldName(), file); } } } catch (Exception e) { e.printStackTrace(); } } }
Example 12
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 13
Source File: ModDocF.java From openprodoc with GNU Affero General Public License v3.0 | 4 votes |
/** * * @param Req * @throws Exception */ @Override protected void ProcessPage(HttpServletRequest Req, PrintWriter out) throws Exception { String FileName=null; InputStream FileData=null; HashMap <String, String>ListFields=new HashMap(); try { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1000000); ServletFileUpload upload = new ServletFileUpload(factory); boolean isMultipart = ServletFileUpload.isMultipartContent(Req); List items = upload.parseRequest(Req); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) ListFields.put(item.getFieldName(), item.getString()); else { FileName=item.getName(); FileData=item.getInputStream(); } } if (!isMultipart || FileData==null) { out.println("KO"); } else { ListFields=GetDat(Req); PDDocs Doc; DriverGeneric PDSession = getSessOPD(Req); String DType=(String) ListFields.get(PDDocs.fDOCTYPE); if (DType==null) Doc = new PDDocs(PDSession); else Doc = new PDDocs(PDSession, DType); Doc.LoadFull((String) ListFields.get(PDDocs.fPDID)); Record Rec=Doc.getRecSum(); Rec.initList(); Attribute Attr=Rec.nextAttr(); while (Attr!=null) { if (!List.contains(Attr.getName())) { String Val=(String) ListFields.get(Attr.getName()); if (Attr.getType()==Attribute.tBOOLEAN) { if(Val == null || Val.length()==0 || Val.equals("0")) Attr.setValue(false); else Attr.setValue(true); } else if(Val != null) { SParent.FillAttr(Req, Attr, Val, false); } } Attr=Rec.nextAttr(); } Doc.assignValues(Rec); Doc.setParentId(ListFields.get("CurrFold")); Doc.setName(FileName); PDMimeType mt=new PDMimeType(PDSession); Doc.setMimeType(mt.SolveName(FileName)); Doc.setStream(FileData); Doc.update(); out.println(UpFileStatus.SetResultOk(Req, "")); } } catch (Exception e) { out.println(UpFileStatus.SetResultKo(Req, e.getLocalizedMessage())); throw e; } finally { out.close(); } }
Example 14
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 15
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 16
Source File: ImportThesF.java From openprodoc with GNU Affero General Public License v3.0 | 4 votes |
/** * * @param Req * @throws Exception */ protected void ProcessPage(HttpServletRequest Req, PrintWriter out) throws Exception { String FileName=null; InputStream FileData=null; HashMap <String, String>ListFields=new HashMap(); try { DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); boolean isMultipart = ServletFileUpload.isMultipartContent(Req); List items = upload.parseRequest(Req); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) ListFields.put(item.getFieldName(), item.getString()); else { FileName=item.getName(); FileData=item.getInputStream(); } } if (!isMultipart || FileData==null) { out.println("KO"); } else { ListFields=GetDat(Req); String NewThesId=ListFields.get("ThesNum"); String ThesName=ListFields.get("ThesName"); String RootText=ListFields.get("RootText"); String MainLanguage=ListFields.get("MainLanguage"); String SubByLang=ListFields.get("SubByLang"); String Transact=ListFields.get("Transact"); String RetainCodes=ListFields.get("RetainCodes"); DriverGeneric PDSession = getSessOPD(Req); PDThesaur Thes=new PDThesaur(PDSession); Thes.Import(ThesName, NewThesId, FileData, MainLanguage, RootText, SubByLang.equals("1"), Transact.equals("1"), RetainCodes.equals("1")); FileData.close(); out.println(UpFileStatus.SetResultOk(Req, Thes.getImportReport())); } } catch (Exception e) { out.println(UpFileStatus.SetResultKo(Req, e.getLocalizedMessage())); throw e; } }
Example 17
Source File: ContribRes.java From openprodoc with GNU Affero General Public License v3.0 | 4 votes |
static synchronized private String GenHtml(HttpServletRequest Req, DriverGeneric LocalSess, ContribConf ConfContrib, PDFolders FoldUser) throws Exception { String HtmlFinal; String Agent=Req.getHeader("User-Agent"); String DimHtml=ConfContrib.SolveHtmlRes(Agent); if (DimHtml!=null) { HtmlFinal=getHtml(LocalSess, DimHtml); } else HtmlFinal=HtmlBase; if (ConfContrib.getFormContribCSS()!=null) { if (ConfContrib.getFormContribCSS().startsWith("http")) HtmlFinal=HtmlFinal.replace("@CSS@", "<link rel=\"STYLESHEET\" type=\"text/css\" href=\""+ConfContrib.getFormContribCSS()+"\"/>"); else HtmlFinal=HtmlFinal.replace("@CSS@", GenCSS(LocalSess, ConfContrib.getFormContribCSS())); } else HtmlFinal=HtmlFinal.replace("@CSS@", ""); if (!ServletFileUpload.isMultipartContent(Req)) { HtmlFinal=HtmlFinal.replace("@RESULT@", "<div class=\"CONTRIBRESKO\">ERROR:NO File<div>"); return(HtmlFinal); } String NameDocT=null; String FileName=null; InputStream FileData=null; HashMap <String, String>ListFields=new HashMap(); DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1000000); ServletFileUpload upload = new ServletFileUpload(factory); upload.setFileSizeMax(ConfContrib.getMaxSize()); List items = upload.parseRequest(Req); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { if (item.getFieldName().equals("CONTRIB_DT")) NameDocT=item.getString("UTF-8"); else { ListFields.put(item.getFieldName(), item.getString("UTF-8")); } } else { FileName=item.getName(); FileData=item.getInputStream(); } } if (!ConfContrib.IsAllowedExt(FileName.substring(FileName.lastIndexOf(".")+1))) { HtmlFinal=HtmlFinal.replace("@RESULT@", "<div class=\"CONTRIBRESKO\">ERROR:Not Allowed extension<div>"); return(HtmlFinal); } PDDocs DocTmp=new PDDocs(LocalSess, NameDocT); DocTmp.setName(FileName); DocTmp.setStream(FileData); Record AttrDef = DocTmp.getRecSum(); for (Map.Entry<String, String> entry : ListFields.entrySet()) { if (AttrDef.getAttr(entry.getKey())!=null); AttrDef.getAttr(entry.getKey()).Import(entry.getValue()); } DocTmp.assignValues(AttrDef); DocTmp.setParentId(FoldUser.getPDId()); DocTmp.setACL(FoldUser.getACL()); try { DocTmp.insert(); HtmlFinal=HtmlFinal.replace("@RESULT@", "<div class=\"CONTRIBRESOK\">"+ConfContrib.getOKMsg()+"</div>"); HtmlFinal=HtmlFinal.replace("CONTRIBRETRYKO", "CONTRIBRETRYOK"); } catch (Exception Ex) { HtmlFinal=HtmlFinal.replace("@RESULT@", "<div class=\"CONTRIBRESKO\">ERROR:"+Ex.getLocalizedMessage()+"<div>"); } return(HtmlFinal); }
Example 18
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 19
Source File: UpgradeWebConsole.java From sling-whiteboard with Apache License 2.0 | 4 votes |
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (ServletFileUpload.isMultipartContent(req)) { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload upload = new ServletFileUpload(factory); InputStream jarIs = null; List<FileItem> formItems; try { formItems = upload.parseRequest(req); if (formItems != null && !formItems.isEmpty()) { for (FileItem it : formItems) { if (it != null && !it.isFormField()) { jarIs = it.getInputStream(); break; } } } } catch (IOException | FileUploadException e1) { log.error("Exception reading file input", e1); throw new ServletException(e1); } // start the html response, write the header, open body and main div PrintWriter pw = startResponse(req, resp); // render top navigation renderTopNavigation(req, pw); // wrap content in a separate div pw.println("<div id='content'>"); renderContent(req, resp); writeUpgradeInfo(resp, jarIs); pw.println("</div>"); // close the main div, body, and html endResponse(pw); } }
Example 20
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 ); } } }