List of usage examples for org.apache.commons.fileupload FileItem getString
String getString(String encoding) throws UnsupportedEncodingException;
From source file:com.ikon.servlet.admin.CheckTextExtractionServlet.java
@SuppressWarnings("unchecked") public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { log.debug("doPost({}, {})", request, response); request.setCharacterEncoding("UTF-8"); updateSessionManager(request);/* ww w.j a v a 2 s . c o m*/ InputStream is = null; try { if (ServletFileUpload.isMultipartContent(request)) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); String docUuid = null; String repoPath = null; String text = null; String mimeType = null; String extractor = null; for (Iterator<FileItem> it = items.iterator(); it.hasNext();) { FileItem item = it.next(); if (item.isFormField()) { if (item.getFieldName().equals("docUuid")) { docUuid = item.getString("UTF-8"); } else if (item.getFieldName().equals("repoPath")) { repoPath = item.getString("UTF-8"); } } else { is = item.getInputStream(); String name = FilenameUtils.getName(item.getName()); mimeType = MimeTypeConfig.mimeTypes.getContentType(name.toLowerCase()); if (!name.isEmpty() && item.getSize() > 0) { docUuid = null; repoPath = null; } else if (docUuid.isEmpty() && repoPath.isEmpty()) { mimeType = null; } } } if (docUuid != null && !docUuid.isEmpty()) { repoPath = OKMRepository.getInstance().getNodePath(null, docUuid); } if (repoPath != null && !repoPath.isEmpty()) { String name = PathUtils.getName(repoPath); mimeType = MimeTypeConfig.mimeTypes.getContentType(name.toLowerCase()); is = OKMDocument.getInstance().getContent(null, repoPath, false); } long begin = System.currentTimeMillis(); if (is != null) { if (!MimeTypeConfig.MIME_UNDEFINED.equals(mimeType)) { TextExtractor extClass = RegisteredExtractors.getTextExtractor(mimeType); if (extClass != null) { extractor = extClass.getClass().getCanonicalName(); text = RegisteredExtractors.getText(mimeType, null, is); } else { extractor = "Undefined text extractor"; } } } ServletContext sc = getServletContext(); sc.setAttribute("docUuid", docUuid); sc.setAttribute("repoPath", repoPath); sc.setAttribute("text", text); sc.setAttribute("time", System.currentTimeMillis() - begin); sc.setAttribute("mimeType", mimeType); sc.setAttribute("extractor", extractor); sc.getRequestDispatcher("/admin/check_text_extraction.jsp").forward(request, response); } } catch (DatabaseException e) { sendErrorRedirect(request, response, e); } catch (FileUploadException e) { sendErrorRedirect(request, response, e); } catch (PathNotFoundException e) { sendErrorRedirect(request, response, e); } catch (AccessDeniedException e) { sendErrorRedirect(request, response, e); } catch (RepositoryException e) { sendErrorRedirect(request, response, e); } finally { IOUtils.closeQuietly(is); } }
From source file:corpixmgr.handler.CorpixPostHandler.java
/** * Parse the import params from the request * @param request the http request//from w w w . ja v a 2 s. com */ protected void parseImportParams(HttpServletRequest request) throws CorpixException { try { boolean isMultipart = ServletFileUpload.isMultipartContent(request); //System.out.println("Parsing import params"); if (isMultipart) { FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request List items = upload.parseRequest(request); for (int i = 0; i < items.size(); i++) { FileItem item = (FileItem) items.get(i); if (item.isFormField()) { String fieldName = item.getFieldName(); if (fieldName != null) { String contents = item.getString("UTF-8"); processField(fieldName, contents); } } else if (item.getName().length() > 0) { fileName = item.getName(); InputStream is = item.getInputStream(); ByteArrayOutputStream bh = new ByteArrayOutputStream(); while (is.available() > 0) { byte[] b = new byte[is.available()]; is.read(b); bh.write(b); } fileData = bh.toByteArray(); } } } else { Map tbl = request.getParameterMap(); Set<String> keys = tbl.keySet(); Iterator<String> iter = keys.iterator(); while (iter.hasNext()) { String key = iter.next(); String[] values = (String[]) tbl.get(key); for (int i = 0; i < values.length; i++) processField(key, values[i]); } } } catch (Exception e) { throw new CorpixException(e); } }
From source file:com.bigdata.rockstor.console.UploadServlet.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (!ServletFileUpload.isMultipartContent(req)) { LOG.error("It is not a MultipartContent, return error."); resp.sendError(500, "It is not a MultipartContent, return error."); return;// w w w.j a v a 2 s.com } FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setFileSizeMax(1024 * 1024 * 512); List<FileItem> fileItems = null; try { fileItems = upload.parseRequest(req); LOG.info("parse requeset success : items num : " + fileItems.size()); } catch (FileUploadException e) { LOG.error("parse requeset failed !"); resp.sendError(500, "parse requeset failed !"); return; } HashMap<String, String> headMap = new HashMap<String, String>(); FileItem theFile = null; long size = -1; URI uri = null; Iterator<FileItem> iter = fileItems.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { String name = item.getFieldName(); String value = null; try { value = item.getString("UTF-8").trim(); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } LOG.info("Parse head info : " + name + " -- " + value); if (name.equals("ObjName")) { try { uri = new URI(value); } catch (URISyntaxException e) { LOG.info("Parse uri info error : " + value); uri = null; } } else if (name.equals("ObjSize")) { try { size = Long.parseLong(value); } catch (Exception e) { LOG.error("Parse objSize error : " + value); } } else { headMap.put(name, value); } } else { theFile = item; } } if (size == -1 || uri == null || theFile == null || headMap.size() == 0) { LOG.error("Parse upload info error : size==-1 || uri == null || theFile == null || headMap.size()==0"); resp.sendError(500, "Parse upload info error : size==-1 || uri == null || theFile == null || headMap.size()==0"); return; } HttpPut put = new HttpPut(); put.setURI(uri); for (Map.Entry<String, String> e : headMap.entrySet()) { if ("Filename".equals(e.getKey())) continue; put.setHeader(e.getKey(), e.getValue()); } put.setEntity(new InputStreamEntity(theFile.getInputStream(), size)); DefaultHttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(put); if (200 != response.getStatusLine().getStatusCode()) { LOG.error("Put object error : " + response.getStatusLine().getStatusCode() + " : " + response.getStatusLine().getReasonPhrase()); resp.sendError(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()); return; } LOG.info("Put object OK : " + uri); response.setStatusCode(200); }
From source file:com.openkm.servlet.admin.CheckTextExtractionServlet.java
@SuppressWarnings("unchecked") public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { log.debug("doPost({}, {})", request, response); request.setCharacterEncoding("UTF-8"); updateSessionManager(request);/*from ww w . java2s. c o m*/ InputStream is = null; try { if (ServletFileUpload.isMultipartContent(request)) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); String docUuid = null; String repoPath = null; String text = null; String error = null; String mimeType = null; String extractor = null; for (Iterator<FileItem> it = items.iterator(); it.hasNext();) { FileItem item = it.next(); if (item.isFormField()) { if (item.getFieldName().equals("docUuid")) { docUuid = item.getString("UTF-8"); } else if (item.getFieldName().equals("repoPath")) { repoPath = item.getString("UTF-8"); } } else { is = item.getInputStream(); String name = FilenameUtils.getName(item.getName()); mimeType = MimeTypeConfig.mimeTypes.getContentType(name.toLowerCase()); if (!name.isEmpty() && item.getSize() > 0) { docUuid = null; repoPath = null; } else if (docUuid.isEmpty() && repoPath.isEmpty()) { mimeType = null; } } } if (docUuid != null && !docUuid.isEmpty()) { repoPath = OKMRepository.getInstance().getNodePath(null, docUuid); } if (repoPath != null && !repoPath.isEmpty()) { String name = PathUtils.getName(repoPath); mimeType = MimeTypeConfig.mimeTypes.getContentType(name.toLowerCase()); is = OKMDocument.getInstance().getContent(null, repoPath, false); } long begin = System.currentTimeMillis(); if (is != null) { if (!MimeTypeConfig.MIME_UNDEFINED.equals(mimeType)) { TextExtractor extClass = RegisteredExtractors.getTextExtractor(mimeType); if (extClass != null) { try { extractor = extClass.getClass().getCanonicalName(); text = RegisteredExtractors.getText(mimeType, null, is); } catch (Exception e) { error = e.getMessage(); } } else { extractor = "Undefined text extractor"; } } } ServletContext sc = getServletContext(); sc.setAttribute("docUuid", docUuid); sc.setAttribute("repoPath", repoPath); sc.setAttribute("text", text); sc.setAttribute("time", System.currentTimeMillis() - begin); sc.setAttribute("mimeType", mimeType); sc.setAttribute("error", error); sc.setAttribute("extractor", extractor); sc.getRequestDispatcher("/admin/check_text_extraction.jsp").forward(request, response); } } catch (DatabaseException e) { sendErrorRedirect(request, response, e); } catch (FileUploadException e) { sendErrorRedirect(request, response, e); } catch (PathNotFoundException e) { sendErrorRedirect(request, response, e); } catch (AccessDeniedException e) { sendErrorRedirect(request, response, e); } catch (RepositoryException e) { sendErrorRedirect(request, response, e); } finally { IOUtils.closeQuietly(is); } }
From source file:com.aspectran.web.activity.request.multipart.MultipartFormDataParser.java
private String getString(FileItem fileItem, String characterEncoding) throws UnsupportedEncodingException { if (characterEncoding != null) { return fileItem.getString(characterEncoding); } else {/*w w w. j av a2 s . com*/ return fileItem.getString(); } }
From source file:com.lock.unlockInfo.servlet.SubmitUnlockImg.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpResponseModel responseModel = new HttpResponseModel(); try {/*from ww w .j av a 2 s.c o m*/ boolean isMultipart = ServletFileUpload.isMultipartContent(request); // ??? if (isMultipart) { Hashtable<String, String> htSubmitParam = new Hashtable<String, String>(); // ?? List<String> fileList = new ArrayList<String>();// // DiskFileItemFactory?? // ????List // list??? FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); Iterator<FileItem> iterator = items.iterator(); while (iterator.hasNext()) { FileItem item = iterator.next(); if (item.isFormField()) { // ? String sFieldName = item.getFieldName(); String sFieldValue = item.getString("UTF-8"); htSubmitParam.put(sFieldName, sFieldValue); } else { // ,??? String newFileName = System.currentTimeMillis() + "_" + UUID.randomUUID().toString() + ".jpg"; File filePath = new File( getServletConfig().getServletContext().getRealPath(Constants.File_Upload)); if (!filePath.exists()) { filePath.mkdirs(); } File file = new File(filePath, newFileName); if (!file.exists()) { file.createNewFile(); } //? BufferedInputStream bis = new BufferedInputStream(item.getInputStream()); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file)); byte[] b = new byte[1024]; int length = 0; while ((length = bis.read(b)) > 0) { bos.write(b, 0, length); } bos.close(); bis.close(); //?url String fileUrl = request.getRequestURL().toString(); fileUrl = fileUrl.substring(0, fileUrl.lastIndexOf("/")); //?URL fileUrl = fileUrl + Constants.File_Upload + "/" + newFileName; /**/ fileList.add(fileUrl); } } // String unlockInfoId = htSubmitParam.get("UnlockInfoId"); String imgType = htSubmitParam.get("ImgType"); String newFileUrl = fileList.get(0); UnlockInfoService unlockInfoService = (UnlockInfoService) context.getBean("unlockInfoService"); UnlockInfo unlockInfo = unlockInfoService.queryByPK(Long.valueOf(unlockInfoId)); if (imgType.equals("customerIdImg")) { unlockInfo.setCustomerIdImg(newFileUrl); } else if (imgType.equals("customerDrivingLicenseImg")) { unlockInfo.setCustomerDrivingLicenseImg(newFileUrl); } else if (imgType.equals("customerVehicleLicenseImg")) { unlockInfo.setCustomerVehicleLicenseImg(newFileUrl); } else if (imgType.equals("customerBusinessLicenseImg")) { unlockInfo.setCustomerBusinessLicenseImg(newFileUrl); } else if (imgType.equals("customerIntroductionLetterImg")) { unlockInfo.setCustomerIntroductionLetterImg(newFileUrl); } else if (imgType.equals("unlockWorkOrderImg")) { unlockInfo.setUnlockWorkOrderImg(newFileUrl); } /**/ unlockInfoService.update(unlockInfo); } } catch (Exception e) { e.printStackTrace(); responseModel.responseCode = "0"; responseModel.responseMessage = e.toString(); } /* ??? */ response.setHeader("content-type", "text/json;charset=utf-8"); response.getOutputStream().write(responseModel.toByteArray()); }
From source file:edu.cornell.mannlib.vitro.webapp.filestorage.uploadrequest.MultipartHttpServletRequest.java
/** * Parse the multipart request. Store the info about the request parameters * and the uploaded files.//w ww . j a v a 2 s . c o m */ public MultipartHttpServletRequest(HttpServletRequest request, int maxFileSize) throws IOException { super(request); Map<String, List<String>> parameters = new HashMap<String, List<String>>(); Map<String, List<FileItem>> files = new HashMap<String, List<FileItem>>(); File tempDir = figureTemporaryDirectory(request); ServletFileUpload upload = createUploadHandler(maxFileSize, tempDir); parseQueryString(request.getQueryString(), parameters); try { List<FileItem> items = parseRequestIntoFileItems(request, upload); for (FileItem item : items) { // Process a regular form field if (item.isFormField()) { addToParameters(parameters, item.getFieldName(), item.getString("UTF-8")); log.debug("Form field (parameter) " + item.getFieldName() + "=" + item.getString()); } else { addToFileItems(files, item); log.debug("File " + item.getFieldName() + ": " + item.getName()); } } } catch (FileUploadException e) { fileUploadException = e; request.setAttribute(FileUploadServletRequest.FILE_UPLOAD_EXCEPTION, e); } this.parameters = Collections.unmodifiableMap(parameters); log.debug("Parameters are: " + this.parameters); this.files = Collections.unmodifiableMap(files); log.debug("Files are: " + this.files); request.setAttribute(FILE_ITEM_MAP, this.files); }
From source file:cn.vlabs.duckling.vwb.ui.servlet.SimpleUploaderServlet.java
private Map<String, Object> parseFileItem(HttpServletRequest request) throws FileUploadException, UnsupportedEncodingException { DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(fileItemFactory); upload.setHeaderEncoding("UTF-8"); List<?> items = upload.parseRequest(request); Map<String, Object> fields = new HashMap<String, Object>(); Iterator<?> iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { fields.put(item.getFieldName(), item.getString("UTF-8")); } else {/* w w w . ja v a 2 s . com*/ fields.put(item.getFieldName(), item); } } return fields; }
From source file:mml.handler.post.MMLPostHandler.java
/** * Parse the import params from the request * @param request the http request//from w ww. j av a 2 s . c o m */ void parseImportParams(HttpServletRequest request) throws MMLException { try { FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request List items = upload.parseRequest(request); for (int i = 0; i < items.size(); i++) { FileItem item = (FileItem) items.get(i); if (item.isFormField()) { String fieldName = item.getFieldName(); if (fieldName != null) { String contents = item.getString(this.encoding); if (fieldName.equals(Params.DOCID)) { int index = contents.lastIndexOf("."); if (index != -1) contents = contents.substring(0, index); docid = contents; } else if (fieldName.equals(Params.AUTHOR)) this.author = contents; else if (fieldName.equals(Params.TITLE)) this.title = contents; else if (fieldName.equals(Params.STYLE)) this.style = contents; else if (fieldName.equals(Params.FORMAT)) this.format = contents; else if (fieldName.equals(Params.SECTION)) this.section = contents; else if (fieldName.equals(Params.VERSION1)) this.version1 = contents; else if (fieldName.equals(Params.ENCODING)) encoding = contents; else if (fieldName.equals(Params.ANNOTATIONS)) annotations = (JSONArray) JSONValue.parse(contents); } } else if (item.getName().length() > 0) { try { // item.getName retrieves the ORIGINAL file name String type = item.getContentType(); if (type != null) { if (type.startsWith("image/")) { InputStream is = item.getInputStream(); ByteHolder bh = new ByteHolder(); while (is.available() > 0) { byte[] b = new byte[is.available()]; is.read(b); bh.append(b); } ImageFile iFile = new ImageFile(item.getName(), item.getContentType(), bh.getData()); if (images == null) images = new ArrayList<ImageFile>(); images.add(iFile); } else if (type.equals("text/plain")) { InputStream is = item.getInputStream(); ByteHolder bh = new ByteHolder(); while (is.available() > 0) { byte[] b = new byte[is.available()]; is.read(b); bh.append(b); } String style = new String(bh.getData(), encoding); if (files == null) files = new ArrayList<String>(); files.add(style); } } } catch (Exception e) { throw new MMLException(e); } } } } catch (Exception e) { throw new MMLException(e); } }
From source file:com.ikon.servlet.admin.CronTabServlet.java
@Override @SuppressWarnings("unchecked") public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { log.debug("doPost({}, {})", request, response); request.setCharacterEncoding("UTF-8"); String action = ""; String userId = request.getRemoteUser(); updateSessionManager(request);/*from ww w . ja va 2 s .c o m*/ try { if (ServletFileUpload.isMultipartContent(request)) { InputStream is = null; FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); CronTab ct = new CronTab(); for (Iterator<FileItem> it = items.iterator(); it.hasNext();) { FileItem item = it.next(); if (item.isFormField()) { if (item.getFieldName().equals("action")) { action = item.getString("UTF-8"); } else if (item.getFieldName().equals("ct_id")) { ct.setId(Integer.parseInt(item.getString("UTF-8"))); } else if (item.getFieldName().equals("ct_name")) { ct.setName(item.getString("UTF-8")); } else if (item.getFieldName().equals("ct_mail")) { ct.setMail(item.getString("UTF-8")); } else if (item.getFieldName().equals("ct_expression")) { ct.setExpression(item.getString("UTF-8")); } else if (item.getFieldName().equals("ct_active")) { ct.setActive(true); } } else { is = item.getInputStream(); ct.setFileName(FilenameUtils.getName(item.getName())); ct.setFileContent(SecureStore.b64Encode(IOUtils.toByteArray(is))); ct.setFileMime(MimeTypeConfig.mimeTypes.getContentType(item.getName())); is.close(); } } if (action.equals("create")) { CronTabDAO.create(ct); // Activity log UserActivity.log(userId, "ADMIN_CRONTAB_CREATE", null, null, ct.toString()); list(request, response); } else if (action.equals("edit")) { CronTabDAO.update(ct); // Activity log UserActivity.log(userId, "ADMIN_CRONTAB_EDIT", Long.toString(ct.getId()), null, ct.toString()); list(request, response); } else if (action.equals("delete")) { CronTabDAO.delete(ct.getId()); // Activity log UserActivity.log(userId, "ADMIN_CRONTAB_DELETE", Long.toString(ct.getId()), null, null); list(request, response); } } } catch (DatabaseException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } catch (FileUploadException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } }