List of usage examples for org.apache.commons.fileupload FileItem getName
String getName();
From source file:controller.file.FileUploader.java
public static void fileUploader(HttpServletRequest req, HttpServletResponse resp) { try {/* w w w .j a v a 2 s . c o m*/ DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory); List<FileItem> items = servletFileUpload.parseRequest(req); Iterator<FileItem> iterator = items.iterator(); while (iterator.hasNext()) { FileItem item = iterator.next(); if (item.isFormField()) { String fileName = item.getFieldName(); String value = item.getString(); System.out.println(fileName); System.out.println(value); } else { if (!item.isFormField()) { item.write(new File("/tmp/" + item.getName())); } } } } catch (FileUploadException ex) { Logger.getLogger(FileUploader.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(FileUploader.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:beans.service.FileUploadTool.java
static public String FileUpload(Map<String, String> fields, List<String> filesOnServer, HttpServletRequest request, HttpServletResponse response) { boolean isMultipart = ServletFileUpload.isMultipartContent(request); DiskFileItemFactory factory = new DiskFileItemFactory(); int MaxMemorySize = 10000000; int MaxRequestSize = MaxMemorySize; String tmpDir = System.getProperty("TMP", "/tmp"); System.out.printf("temporary directory:%s", tmpDir); factory.setSizeThreshold(MaxMemorySize); factory.setRepository(new File(tmpDir)); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Set overall request size constraint upload.setSizeMax(MaxRequestSize);//from ww w . j av a2 s . c om // Parse the request try { List<FileItem> items = upload.parseRequest(request); // Process the uploaded items Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (item.isFormField()) {//k -v String name = item.getFieldName(); String value = item.getString(); fields.put(name, value); } else { String fieldName = item.getFieldName(); String fileName = item.getName(); if (fileName == null || fileName.length() < 1) { return "file name is empty."; } String localFileName = ServletConfig.fileServerRootDir + File.separator + "tmp" + File.separator + fileName; System.out.printf("upload file:%s", localFileName); String contentType = item.getContentType(); boolean isInMemory = item.isInMemory(); long sizeInBytes = item.getSize(); File uploadedFile = new File(localFileName); item.write(uploadedFile); filesOnServer.add(localFileName); } } return "success"; } catch (FileUploadException e) { e.printStackTrace(); return e.toString(); } catch (Exception e) { e.printStackTrace(); return e.toString(); } }
From source file:edu.isi.karma.util.FileUtil.java
static public File downloadFileFromHTTPRequest(HttpServletRequest request, String destinationDirString) { // Download the file to the upload file folder File destinationDir = new File(destinationDirString); logger.debug("File upload destination directory: " + destinationDir.getAbsolutePath()); DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); // Set the size threshold, above which content will be stored on disk. fileItemFactory.setSizeThreshold(1 * 1024 * 1024); //1 MB //Set the temporary directory to store the uploaded files of size above threshold. fileItemFactory.setRepository(destinationDir); ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory); File uploadedFile = null;/* www . ja v a 2s . c om*/ try { // Parse the request @SuppressWarnings("rawtypes") List items = uploadHandler.parseRequest(request); @SuppressWarnings("rawtypes") Iterator itr = items.iterator(); while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); // Ignore Form Fields. if (item.isFormField()) { // Do nothing } else { //Handle Uploaded files. Write file to the ultimate location. uploadedFile = new File(destinationDir, item.getName()); if (item instanceof DiskFileItem) { DiskFileItem t = (DiskFileItem) item; if (!t.getStoreLocation().renameTo(uploadedFile)) item.write(uploadedFile); } else item.write(uploadedFile); } } } catch (FileUploadException ex) { logger.error("Error encountered while parsing the request", ex); } catch (Exception ex) { logger.error("Error encountered while uploading file", ex); } return uploadedFile; }
From source file:com.gtwm.pb.servlets.ServletUtilMethods.java
/** * Replacement for and wrapper around/*from w ww . ja va 2 s . co m*/ * HttpServletRequest.getParameter(String) which works for multi-part form * data as well as normal requests */ public static String getParameter(HttpServletRequest request, String parameterName, List<FileItem> multipartItems) { if (FileUpload.isMultipartContent(new ServletRequestContext(request))) { for (FileItem item : multipartItems) { if (item.getFieldName().equals(parameterName)) { if (item.isFormField()) { return item.getString(); } else { return item.getName(); } } } return null; } else { return request.getParameter(parameterName); } }
From source file:com.krawler.esp.handlers.fileUploader.java
public static HrmsDocs uploadFile(Session session, FileItem fi, String userid, HashMap arrparam, boolean flag) throws ServiceException, SessionExpiredException, UnsupportedEncodingException { HrmsDocs docObj = new HrmsDocs(); User userObj = null;/*from www.j a v a 2s . com*/ Jobapplicant jobapp = null; try { String fileName = new String(fi.getName().getBytes(), "UTF8"); String Ext = ""; if (fileName.contains(".")) { Ext = fileName.substring(fileName.lastIndexOf(".")); } if (flag) { userObj = (User) session.get(User.class, userid); docObj.setUserid(userObj); } else { jobapp = (Jobapplicant) session.get(Jobapplicant.class, userid); docObj.setApplicantid(jobapp); } docObj.setDocname(fileName); docObj.setStorename(""); docObj.setDoctype(""); docObj.setUploadedon(new Date()); docObj.setStorageindex(1); docObj.setDocsize(fi.getSize() + ""); docObj.setDeleted(false); if (StringUtil.isNullOrEmpty((String) arrparam.get("docname")) == false) { docObj.setDispdocname((String) arrparam.get("docname")); } if (StringUtil.isNullOrEmpty((String) arrparam.get("docdesc")) == false) { docObj.setDocdesc((String) arrparam.get("docdesc")); } session.save(docObj); String fileid = docObj.getDocid(); if (Ext.length() > 0) { fileid = fileid + Ext; } docObj.setStorename(fileid); session.update(docObj); String temp = StorageHandler.GetDocStorePath1(); uploadFile(fi, temp, fileid); } catch (ServiceException e) { throw ServiceException.FAILURE(e.getMessage(), e); } return docObj; }
From source file:msec.org.FileUploadServlet.java
static protected String FileUpload(Map<String, String> fields, List<String> filesOnServer, HttpServletRequest request, HttpServletResponse response) { boolean isMultipart = ServletFileUpload.isMultipartContent(request); // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); int MaxMemorySize = 10000000; int MaxRequestSize = MaxMemorySize; String tmpDir = System.getProperty("TMP", "/tmp"); //System.out.printf("temporary directory:%s", tmpDir); // Set factory constraints factory.setSizeThreshold(MaxMemorySize); factory.setRepository(new File(tmpDir)); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("utf8"); // Set overall request size constraint upload.setSizeMax(MaxRequestSize);//from w w w .j a va 2 s .c o m // Parse the request try { @SuppressWarnings("unchecked") List<FileItem> items = upload.parseRequest(request); // Process the uploaded items Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (item.isFormField()) {//k -v String name = item.getFieldName(); String value = item.getString("utf-8"); fields.put(name, value); } else { String fieldName = item.getFieldName(); String fileName = item.getName(); if (fileName == null || fileName.length() < 1) { return "file name is empty."; } String localFileName = ServletConfig.fileServerRootDir + File.separator + "tmp" + File.separator + fileName; //System.out.printf("upload file:%s", localFileName); String contentType = item.getContentType(); boolean isInMemory = item.isInMemory(); long sizeInBytes = item.getSize(); File uploadedFile = new File(localFileName); item.write(uploadedFile); filesOnServer.add(localFileName); } } return "success"; } catch (FileUploadException e) { e.printStackTrace(); return e.toString(); } catch (Exception e) { e.printStackTrace(); return e.toString(); } }
From source file:com.krawler.esp.handlers.fileUploader.java
public static HrmsDocs uploadFile(Session session, FileItem fi, ConfigRecruitmentData ConfigRecruitmentDataobj, HashMap arrparam, boolean flag) throws ServiceException, SessionExpiredException, UnsupportedEncodingException { HrmsDocs docObj = new HrmsDocs(); User userObj = null;/*from www . j a v a 2 s.c o m*/ Jobapplicant jobapp = null; try { String fileName = new String(fi.getName().getBytes(), "UTF8"); String Ext = ""; if (fileName.contains(".")) { Ext = fileName.substring(fileName.lastIndexOf(".")); } docObj.setDocname(fileName); docObj.setReferenceid(ConfigRecruitmentDataobj.getId()); docObj.setStorename(""); docObj.setDoctype(""); docObj.setUploadedon(new Date()); docObj.setUploadedby(ConfigRecruitmentDataobj.getCol1() + " " + ConfigRecruitmentDataobj.getCol2()); docObj.setStorageindex(1); docObj.setDocsize(fi.getSize() + ""); docObj.setDeleted(false); if (!StringUtil.isNullOrEmpty((String) arrparam.get("docname"))) { docObj.setDispdocname((String) arrparam.get("docname")); } if (!StringUtil.isNullOrEmpty((String) arrparam.get("docdesc"))) { docObj.setDocdesc((String) arrparam.get("docdesc")); } session.save(docObj); String fileid = docObj.getDocid(); if (Ext.length() > 0) { fileid = fileid + Ext; } docObj.setStorename(fileid); session.update(docObj); String temp = StorageHandler.GetDocStorePath1(); uploadFile(fi, temp, fileid); } catch (ServiceException e) { throw ServiceException.FAILURE(e.getMessage(), e); } return docObj; }
From source file:dk.kontentsu.api.exposure.ItemExposure.java
private static InputStream getInputStream(final FileItem m) { try {/* www.j a va2 s. c om*/ return m.getInputStream(); } catch (IOException ex) { throw new ApiErrorException( "Error processing multipart data - unable to get input stream for reference " + m.getName(), ex); } }
From source file:com.liferay.apio.architect.internal.body.MultipartToBodyConverter.java
private static void _storeFileItem(FileItem fileItem, Consumer<String> valueConsumer, Consumer<BinaryFile> fileConsumer) { try {// w w w. ja va2 s . c o m if (fileItem.isFormField()) { InputStream stream = fileItem.getInputStream(); valueConsumer.accept(Streams.asString(stream)); } else { BinaryFile binaryFile = new BinaryFile(fileItem.getInputStream(), fileItem.getSize(), fileItem.getContentType(), fileItem.getName()); fileConsumer.accept(binaryFile); } } catch (IOException ioe) { throw new BadRequestException("Invalid body", ioe); } }
From source file:fr.paris.lutece.portal.web.xsl.XslExportJspBean.java
/** * Get a file contained in the request from the name of the parameter * * @param strFileInputName name of the file parameter of the request * @param request the request//ww w .j a v a2s .co m * @return file the file contained in the request with the given parameter key */ private static File getFileData(String strFileInputName, HttpServletRequest request) { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; FileItem fileItem = multipartRequest.getFile(strFileInputName); if ((fileItem != null) && (fileItem.getName() != null) && !EMPTY_STRING.equals(fileItem.getName())) { File file = new File(); PhysicalFile physicalFile = new PhysicalFile(); physicalFile.setValue(fileItem.get()); file.setTitle(FileUploadService.getFileNameOnly(fileItem)); file.setSize((int) fileItem.getSize()); file.setPhysicalFile(physicalFile); file.setMimeType(FileSystemUtil.getMIMEType(FileUploadService.getFileNameOnly(fileItem))); return file; } return null; }