Java Code Examples for org.apache.commons.fileupload.servlet.ServletFileUpload#parseRequest()
The following examples show how to use
org.apache.commons.fileupload.servlet.ServletFileUpload#parseRequest() .
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: PackageServletHandler.java From urule with Apache License 2.0 | 6 votes |
public void importExcelTemplate(HttpServletRequest req, HttpServletResponse resp) throws Exception { DiskFileItemFactory factory=new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(req); Iterator<FileItem> itr = items.iterator(); List<Map<String,Object>> mapData=null; while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); String name=item.getFieldName(); if(!name.equals("file")){ continue; } InputStream stream=item.getInputStream(); mapData=parseExcel(stream); httpSessionKnowledgeCache.put(req, IMPORT_EXCEL_DATA, mapData); stream.close(); break; } httpSessionKnowledgeCache.put(req, IMPORT_EXCEL_DATA, mapData); writeObjectToJson(resp, mapData); }
Example 2
Source File: PoseidonServlet.java From Poseidon with Apache License 2.0 | 6 votes |
private void handleFileUpload(PoseidonRequest request, HttpServletRequest httpRequest) throws IOException { // If uploaded file size is more than 10KB, will be stored in disk DiskFileItemFactory factory = new DiskFileItemFactory(); File repository = new File(FILE_UPLOAD_TMP_DIR); if (repository.exists()) { factory.setRepository(repository); } // Currently we don't impose max file size at container layer. Apps can impose it by checking FileItem // Apps also have to delete tmp file explicitly (if at all it went to disk) ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> fileItems = null; try { fileItems = upload.parseRequest(httpRequest); } catch (FileUploadException e) { throw new IOException(e); } for (FileItem fileItem : fileItems) { String name = fileItem.getFieldName(); if (fileItem.isFormField()) { request.setAttribute(name, new String[] { fileItem.getString() }); } else { request.setAttribute(name, fileItem); } } }
Example 3
Source File: AvatarUploadController.java From airsonic-advanced with GNU General Public License v3.0 | 5 votes |
@PostMapping protected ModelAndView handleRequestInternal(HttpServletRequest request) 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<FileItem> items = upload.parseRequest(request); // Look for file items. for (FileItem item : items) { 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)); return new ModelAndView("avatarUploadResult","model",map); }
Example 4
Source File: FileHandle.java From fixflow with Apache License 2.0 | 5 votes |
public static Iterator<FileItem> createFactory(HttpServletRequest request, HttpServletResponse response) throws Exception{ try{ // 创建一个磁盘文件的工厂,然后将它 传递到servletFileUplaod的实例中 DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); ServletFileUpload servletFileUpload = new ServletFileUpload( diskFileItemFactory); // 根据request对象获取所有的文件集合,这里包括input标签输入的值也属于FileInput List<FileItem> fileItemList = servletFileUpload.parseRequest(request); return fileItemList.iterator(); } catch (Exception e) { e.printStackTrace(); throw new Exception("磁盘文件的工厂创建失败!"); } }
Example 5
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 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: UploadServlet.java From tutorials with MIT License | 5 votes |
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (ServletFileUpload.isMultipartContent(request)) { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(MEMORY_THRESHOLD); factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload upload = new ServletFileUpload(factory); upload.setFileSizeMax(MAX_FILE_SIZE); upload.setSizeMax(MAX_REQUEST_SIZE); String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY; File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdir(); } try { List<FileItem> formItems = upload.parseRequest(request); if (formItems != null && formItems.size() > 0) { for (FileItem item : formItems) { if (!item.isFormField()) { String fileName = new File(item.getName()).getName(); String filePath = uploadPath + File.separator + fileName; File storeFile = new File(filePath); item.write(storeFile); request.setAttribute("message", "File " + fileName + " has uploaded successfully!"); } } } } catch (Exception ex) { request.setAttribute("message", "There was an error: " + ex.getMessage()); } getServletContext().getRequestDispatcher("/result.jsp").forward(request, response); } }
Example 8
Source File: HttpSupport.java From javalite with Apache License 2.0 | 4 votes |
/** * Returns a collection of uploaded files and form fields from a multi-part request. * This method uses <a href="http://commons.apache.org/proper/commons-fileupload/apidocs/org/apache/commons/fileupload/disk/DiskFileItemFactory.html">DiskFileItemFactory</a>. * As a result, it is recommended to add the following to your web.xml file: * * <pre> * <listener> * <listener-class> * org.apache.commons.fileupload.servlet.FileCleanerCleanup * </listener-class> * </listener> *</pre> * * For more information, see: <a href="http://commons.apache.org/proper/commons-fileupload/using.html">Using FileUpload</a> * * @param encoding specifies the character encoding to be used when reading the headers of individual part. * When not specified, or null, the request encoding is used. If that is also not specified, or null, * the platform default encoding is used. * * @param maxUploadSize maximum size of the upload in bytes. A value of -1 indicates no maximum. * * @return a collection of uploaded files from a multi-part request. */ protected List<FormItem> multipartFormItems(String encoding, long maxUploadSize) { //we are thread safe, because controllers are pinned to a thread and discarded after each request. if(RequestContext.getFormItems() != null ){ return RequestContext.getFormItems(); } HttpServletRequest req = RequestContext.getHttpRequest(); if (req instanceof AWMockMultipartHttpServletRequest) {//running inside a test, and simulating upload. RequestContext.setFormItems(((AWMockMultipartHttpServletRequest) req).getFormItems()); } else { if (!ServletFileUpload.isMultipartContent(req)) throw new ControllerException("this is not a multipart request, be sure to add this attribute to the form: ... enctype=\"multipart/form-data\" ..."); DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(Configuration.getMaxUploadSize()); factory.setRepository(Configuration.getTmpDir()); ServletFileUpload upload = new ServletFileUpload(factory); if(encoding != null) upload.setHeaderEncoding(encoding); upload.setFileSizeMax(maxUploadSize); try { List<org.apache.commons.fileupload.FileItem> apacheFileItems = upload.parseRequest(RequestContext.getHttpRequest()); ArrayList items = new ArrayList<>(); for (FileItem apacheItem : apacheFileItems) { ApacheFileItemFacade f = new ApacheFileItemFacade(apacheItem); if(f.isFormField()){ items.add(new FormItem(f)); }else{ items.add(new org.javalite.activeweb.FileItem(f)); } } RequestContext.setFormItems(items); } catch (Exception e) { throw new ControllerException(e); } } return RequestContext.getFormItems(); }
Example 9
Source File: FessMultipartRequestHandler.java From fess with Apache License 2.0 | 4 votes |
protected List<FileItem> parseRequest(final HttpServletRequest request, final ServletFileUpload upload) throws FileUploadException { return upload.parseRequest(request); }
Example 10
Source File: ImportExcelServletAction.java From ureport with Apache License 2.0 | 4 votes |
@Override public void execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String tempDir=System.getProperty("java.io.tmpdir"); FileItemFactory factory=new DiskFileItemFactory(1000240,new File(tempDir)); ServletFileUpload upload=new ServletFileUpload(factory); ReportDefinition report=null; String errorInfo=null; try { List<FileItem> items=upload.parseRequest(req); for(FileItem item:items){ String fieldName=item.getFieldName(); String name=item.getName().toLowerCase(); if(fieldName.equals("_excel_file") && (name.endsWith(".xls") || name.endsWith(".xlsx"))){ InputStream inputStream=item.getInputStream(); for(ExcelParser parser:excelParsers){ if(parser.support(name)){ report=parser.parse(inputStream); break; } } inputStream.close(); break; } } errorInfo="请选择一个合法的Excel导入"; } catch (Exception e) { e.printStackTrace(); errorInfo=e.getMessage(); } Map<String,Object> result=new HashMap<String,Object>(); if(report!=null){ result.put("result", true); TempObjectCache.putObject("classpath:template/template.ureport.xml", report); }else{ result.put("result", false); if(errorInfo!=null){ result.put("errorInfo", errorInfo); } } writeObjectToJson(resp, result); }
Example 11
Source File: VariableEditorServletHandler.java From urule with Apache License 2.0 | 4 votes |
public void importXml(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { DiskFileItemFactory factory = new DiskFileItemFactory(); ServletContext servletContext = req.getSession().getServletContext(); File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir"); factory.setRepository(repository); ServletFileUpload upload = new ServletFileUpload(factory); InputStream inputStream=null; try { List<FileItem> items = upload.parseRequest(req); if(items.size()!=1){ throw new ServletException("Upload xml file is invalid."); } FileItem item=items.get(0); inputStream=item.getInputStream(); String xmlContent=IOUtils.toString(inputStream, "utf-8"); List<Variable> variables=new ArrayList<Variable>(); Document doc=DocumentHelper.parseText(xmlContent); Element root=doc.getRootElement(); String clazz=root.attributeValue("clazz"); for(Object obj:root.elements()){ if(obj==null || !(obj instanceof Element)){ continue; } Element ele=(Element)obj; Variable var=new Variable(); var.setAct(Act.InOut); var.setDefaultValue(ele.attributeValue("defaultValue")); var.setLabel(ele.attributeValue("label")); var.setName(ele.attributeValue("name")); var.setType(Datatype.valueOf(ele.attributeValue("type"))); variables.add(var); } Map<String,Object> result=new HashMap<String,Object>(); result.put("clazz", clazz); result.put("variables", variables); writeObjectToJson(resp, result); } catch (Exception e) { throw new ServletException(e); } finally { IOUtils.closeQuietly(inputStream); } }
Example 12
Source File: AttachmentServlet.java From swellrt 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); boolean isAuthorized = waveletProvider.checkAccessPermission(waveletName, user); if (!isAuthorized) { response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } String fileName = fileItem.getName(); // Get only the file name not whole path. if (fileName != null) { fileName = FilenameUtils.getName(fileName); 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 13
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 14
Source File: EntitlementPolicyAdminServiceClient.java From carbon-identity-framework with Apache License 2.0 | 4 votes |
/** * @param requestContext * @return * @throws FileUploadException */ private List parseRequest(ServletRequestContext requestContext) throws FileUploadException { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); return upload.parseRequest(requestContext); }
Example 15
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 16
Source File: ImportDocRIS.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); String ParentId=ListFields.get("CurrFold"); String RISType=ListFields.get("RISType"); PDDocsRIS D=new PDDocsRIS(SParent.getSessOPD(Req), RISType); D.ImportFileRIS(ParentId, FileData); out.println(UpFileStatus.SetResultOk(Req, "")); FileData.close(); } } catch (Exception e) { out.println(UpFileStatus.SetResultKo(Req, e.getLocalizedMessage())); throw e; } }
Example 17
Source File: ImpElemF.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; 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(); break; } } DriverGeneric PDSession=SParent.getSessOPD(Req); DocumentBuilder DB = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document XMLObjects = DB.parse(FileData); NodeList OPDObjectList = XMLObjects.getElementsByTagName(ObjPD.XML_OPDObject); Node OPDObject; ObjPD Obj2Build; int Tot=0; for (int i=0; i<OPDObjectList.getLength(); i++) { OPDObject = OPDObjectList.item(i); Obj2Build=PDSession.BuildObj(OPDObject); Obj2Build.ProcesXMLNode(OPDObject); Tot++; } DB.reset(); out.println(UpFileStatus.SetResultOk(Req, "Total="+Tot)); FileData.close(); } catch (Exception e) { out.println(UpFileStatus.SetResultKo(Req, e.getLocalizedMessage())); throw e; } }
Example 18
Source File: UploadFileController.java From erp-framework with MIT License | 4 votes |
@RequestMapping("/uploadImg") @ResponseBody public ResultBean uploadImg(Long classesId, HttpServletRequest request) { List<Map<String, Object>> resultPath = new ArrayList<Map<String, Object>>(); try { // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Set factory constraints // 设置缓冲区大小,这里是4kb factory.setSizeThreshold(4096); // 设置缓冲区目录 factory.setRepository(null); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Set overall request size constraint // 设置最大文件尺寸,这里是4MB upload.setSizeMax(4194304); // 得到所有的文件 List<FileItem> items = upload.parseRequest(request); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); // 文件夹 String uploadDir = REAL_PATH + File.separator + sdf.format(new Date()); //虚拟路径 String uploadVirPath = TEMP_PATH + File.separator + sdf.format(new Date()); Iterator<FileItem> i = items.iterator(); while (i.hasNext()) { FileItem fi = i.next(); String fileName = fi.getName(); if (fileName != null) { // 解决文件名乱码问题 File fullFile = new File(new String(fi.getName().getBytes(), "utf-8")); File savedFile = new File(uploadDir, fullFile.getName()); if (!savedFile.getParentFile().exists()) { savedFile.getParentFile().mkdir(); } if (!savedFile.exists()) { savedFile.createNewFile(); } Map<String, Object> map = new HashMap<String, Object>(); map.put("url", uploadVirPath + "/" + fullFile.getName()); map.put("fileSize", (fi.getSize())); fi.write(savedFile); resultPath.add(map); } } } catch (Exception e) { e.printStackTrace(); } return new ResultBean(resultPath); }
Example 19
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 20
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(); } }