List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload parseRequest
public List parseRequest(HttpServletRequest request) throws FileUploadException
From source file:mercury.Controller.java
public void putAllRequestParametersInAttributes(HttpServletRequest request) { ArrayList fileBeanList = new ArrayList(); HashMap<String, String> ht = new HashMap<String, String>(); String fieldName = null;//from w ww. j a v a2 s . c o m String fieldValue = null; boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); java.util.List items = null; try { items = upload.parseRequest(request); } catch (FileUploadException e) { e.printStackTrace(); } Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { fieldName = item.getFieldName(); fieldValue = item.getString(); ht.put(fieldName, fieldValue); } else if (!item.isFormField()) { UploadedFileBean bean = new UploadedFileBean(); bean.setFileItem(item); bean.setContentType(item.getContentType()); bean.setFileName(item.getName()); try { bean.setInputStream(item.getInputStream()); } catch (Exception e) { System.out.println("=== Erro: " + e); } bean.setIsInMemory(item.isInMemory()); bean.setSize(item.getSize()); fileBeanList.add(bean); request.getSession().setAttribute("UPLOADED_FILE", bean); } } } else if (!isMultipart) { Enumeration<String> en = request.getParameterNames(); String name = null; String value = null; while (en.hasMoreElements()) { name = en.nextElement(); value = request.getParameter(name); ht.put(name, value); } } request.setAttribute("REQUEST_PARAMETERS", ht); }
From source file:com.primeleaf.krystal.web.action.console.UpdateProfilePictureAction.java
@SuppressWarnings("rawtypes") public WebView execute(HttpServletRequest request, HttpServletResponse response) throws Exception { request.setCharacterEncoding(HTTPConstants.CHARACTER_ENCODING); HttpSession session = request.getSession(); User loggedInUser = (User) session.getAttribute(HTTPConstants.SESSION_KRYSTAL); if (request.getMethod().equalsIgnoreCase("POST")) { try {// ww w.j a v a 2s . co m String userName = loggedInUser.getUserName(); String sessionid = (String) session.getId(); String tempFilePath = System.getProperty("java.io.tmpdir"); if (!(tempFilePath.endsWith("/") || tempFilePath.endsWith("\\"))) { tempFilePath += System.getProperty("file.separator"); } tempFilePath += userName + "_" + sessionid; //variables String fileName = "", ext = ""; File file = null; // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); request.setCharacterEncoding(HTTPConstants.CHARACTER_ENCODING); upload.setHeaderEncoding(HTTPConstants.CHARACTER_ENCODING); List listItems = upload.parseRequest((HttpServletRequest) request); Iterator iter = listItems.iterator(); FileItem fileItem = null; while (iter.hasNext()) { fileItem = (FileItem) iter.next(); if (!fileItem.isFormField()) { try { fileName = fileItem.getName(); file = new File(fileName); fileName = file.getName(); ext = fileName.substring(fileName.lastIndexOf(".") + 1).toUpperCase(); if (!"JPEG".equalsIgnoreCase(ext) && !"JPG".equalsIgnoreCase(ext) && !"PNG".equalsIgnoreCase(ext)) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid image. Please upload JPG or PNG file"); return (new MyProfileAction().execute(request, response)); } file = new File(tempFilePath + "." + ext); fileItem.write(file); } catch (Exception ex) { session.setAttribute("UPLOAD_ERROR", ex.getLocalizedMessage()); return (new MyProfileAction().execute(request, response)); } } } //if if (file.length() <= 0) { //code for checking minimum size of file request.setAttribute(HTTPConstants.REQUEST_ERROR, "Zero length document"); return (new MyProfileAction().execute(request, response)); } if (file.length() > (1024 * 1024 * 2)) { //code for checking minimum size of file request.setAttribute(HTTPConstants.REQUEST_ERROR, "Image size too large. Upload upto 2MB file"); return (new MyProfileAction().execute(request, response)); } User user = loggedInUser; user.setProfilePicture(file); UserDAO.getInstance().setProfilePicture(user); AuditLogManager.log(new AuditLogRecord(user.getUserId(), AuditLogRecord.OBJECT_USER, AuditLogRecord.ACTION_EDITED, loggedInUser.getUserName(), request.getRemoteAddr(), AuditLogRecord.LEVEL_INFO, "", "Profile picture update")); } catch (Exception e) { e.printStackTrace(System.out); } } request.setAttribute(HTTPConstants.REQUEST_MESSAGE, "Profile picture uploaded successfully"); return (new MyProfileAction().execute(request, response)); }
From source file:edu.ucla.loni.server.Upload.java
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { if (ServletFileUpload.isMultipartContent(req)) { // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); try {/*w ww. j a v a 2s . c o m*/ @SuppressWarnings("unchecked") List<FileItem> items = upload.parseRequest(req); // Go through the items and get the root and package String rootPath = ""; String packageName = ""; for (FileItem item : items) { if (item.isFormField()) { if (item.getFieldName().equals("root")) { rootPath = item.getString(); } else if (item.getFieldName().equals("packageName")) { packageName = item.getString(); } } } if (rootPath.equals("")) { res.getWriter().println("error :: Root directory has not been found."); return; } Directory root = Database.selectDirectory(rootPath); // Go through items and process urls and files for (FileItem item : items) { // Uploaded File if (item.isFormField() == false) { String filename = item.getName(); ; if (filename.equals("") == true) continue; try { InputStream in = item.getInputStream(); //determine if it is pipefile or zipfile //if it is pipefile => feed directly to writeFile function //otherwise, uncompresse it first and then one-by-one feed to writeFile if (filename.endsWith(".zip")) { ZipInputStream zip = new ZipInputStream(in); ZipEntry entry = zip.getNextEntry(); while (entry != null) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); if (baos != null) { byte[] arr = new byte[4096]; int index = 0; while ((index = zip.read(arr, 0, 4096)) != -1) { baos.write(arr, 0, index); } } InputStream is = new ByteArrayInputStream(baos.toByteArray()); writeFile(root, packageName, is); entry = zip.getNextEntry(); } zip.close(); } else { writeFile(root, packageName, in); } in.close(); } catch (Exception e) { res.getWriter().println("Failed to upload " + filename + ". " + e.getMessage()); } } // URLs if (item.isFormField() && item.getFieldName().equals("urls") && item.getString().equals("") == false) { String urlListAsStr = item.getString(); String[] urlList = urlListAsStr.split("\n"); for (String urlStr : urlList) { try { URL url = new URL(urlStr); URLConnection urlc = url.openConnection(); InputStream in = urlc.getInputStream(); writeFile(root, packageName, in); in.close(); } catch (Exception e) { res.getWriter().println("Failed to upload " + urlStr); return; } } } } } catch (Exception e) { res.getWriter().println("Error occurred while creating file. Error Message : " + e.getMessage()); } } }
From source file:com.carolinarollergirls.scoreboard.jetty.MediaServlet.java
protected void upload(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {//from ww w . j a v a2 s.c om if (!ServletFileUpload.isMultipartContent(request)) { response.sendError(response.SC_BAD_REQUEST); return; } String media = null, type = null; FileItemFactory fiF = new DiskFileItemFactory(); ServletFileUpload sfU = new ServletFileUpload(fiF); List<FileItem> fileItems = new LinkedList<FileItem>(); Iterator i = sfU.parseRequest(request).iterator(); while (i.hasNext()) { FileItem item = (FileItem) i.next(); if (item.isFormField()) { if (item.getFieldName().equals("media")) media = item.getString(); else if (item.getFieldName().equals("type")) type = item.getString(); } else if (item.getName().matches(zipExtRegex)) { processZipFileItem(fiF, item, fileItems); } else if (uploadFileNameFilter.accept(null, item.getName())) { fileItems.add(item); } } if (fileItems.size() == 0) { setTextResponse(response, response.SC_BAD_REQUEST, "No files provided to upload"); return; } processFileItemList(fileItems, media, type); int len = fileItems.size(); setTextResponse(response, response.SC_OK, "Successfully uploaded " + len + " file" + (len > 1 ? "s" : "")); } catch (FileNotFoundException fnfE) { setTextResponse(response, response.SC_NOT_FOUND, fnfE.getMessage()); } catch (IllegalArgumentException iaE) { setTextResponse(response, response.SC_BAD_REQUEST, iaE.getMessage()); } catch (FileUploadException fuE) { setTextResponse(response, response.SC_INTERNAL_SERVER_ERROR, fuE.getMessage()); } }
From source file:com.ts.control.UploadFile.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String campo1 = ""; String campo2 = ""; String campo3 = ""; String campo4 = ""; String campo5 = ""; String campo6 = ""; String campo7 = ""; int c = 1;/* ww w . j a v a2s . c om*/ try { boolean ismultipart = ServletFileUpload.isMultipartContent(request); if (!ismultipart) { } else { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List items = null; try { items = upload.parseRequest(request); } catch (Exception e) { } Iterator itr = items.iterator(); while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); if (item.isFormField()) { } else { String itemname = item.getName(); if ((itemname == null || itemname.equals(""))) { continue; } String filename = FilenameUtils.getName(itemname); System.out.println("ruta---------------" + saveFile + filename); File f = checkExist(filename); item.write(f); //////// List cellDataList = new ArrayList(); try { FileInputStream fileInputStream = new FileInputStream(f); XSSFWorkbook workBook = new XSSFWorkbook(fileInputStream); XSSFSheet hssfSheet = workBook.getSheetAt(0); Iterator rowIterator = hssfSheet.rowIterator(); while (rowIterator.hasNext()) { XSSFRow hssfRow = (XSSFRow) rowIterator.next(); Iterator iterator = hssfRow.cellIterator(); List cellTempList = new ArrayList(); while (iterator.hasNext()) { XSSFCell hssfCell = (XSSFCell) iterator.next(); cellTempList.add(hssfCell); } cellDataList.add(cellTempList); } } catch (Exception e) { e.printStackTrace(); } out.println("<table border='3' class='table table-bordered table-striped table-hover'>"); for (int i = 1; i < cellDataList.size(); i++) { List cellTempList = (List) cellDataList.get(i); out.println("<tr>"); for (int j = 0; j < cellTempList.size(); j++) { XSSFCell hssfCell = (XSSFCell) cellTempList.get(j); String dato = hssfCell.toString(); out.print("<td>" + dato + "</td>"); switch (c) { case 1: campo1 = dato; c++; break; case 2: campo2 = dato; c++; break; case 3: campo3 = dato; c++; break; case 4: campo4 = dato; c++; break; case 5: campo5 = dato; c++; break; case 6: campo6 = dato; c++; break; case 7: campo7 = dato; c = 1; break; } } //model.Consulta.addRegistros(campo1,campo2,campo3,campo4,campo5,campo6,campo7); } out.println("</table><br>"); ///////// } } } } catch (Exception e) { } finally { out.close(); } }
From source file:com.xclinical.mdr.server.DocumentServlet.java
@Override protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { try {/*from w w w. j a v a 2 s .c o m*/ if (ServletFileUpload.isMultipartContent(req)) { log.debug("detected multipart content"); final FileInfo info = new FileInfo(); ServletFileUpload fileUpload = new ServletFileUpload(new DiskFileItemFactory()); @SuppressWarnings("unchecked") List<FileItem> items = fileUpload.parseRequest(req); String session = null; for (Iterator<FileItem> i = items.iterator(); i.hasNext();) { log.debug("detected form field"); FileItem item = (FileItem) i.next(); if (item.isFormField()) { String fieldName = item.getFieldName(); String fieldValue = item.getString(); if (fieldName != null) { log.debug("{0}={1}", fieldName, fieldValue); } else { log.severe("fieldName may not be null"); } if ("session".equals(fieldName)) { session = fieldValue; } } else { log.debug("detected content"); info.contentName = item.getName(); info.contentName = new File(info.contentName).getName(); info.contentType = item.getContentType(); info.content = item.get(); log.debug("{0} bytes", info.content.length); } } if (info.content == null) throw new IllegalArgumentException("there is no content"); if (info.contentType == null) throw new IllegalArgumentException("There is no content type"); if (info.contentName == null) throw new IllegalArgumentException("There is no content name"); Session.runInSession(session, new Callable<Void>() { @Override public Void call() throws Exception { Document document = Document.create(info.contentName, info.contentType, info.content); log.info("Created document " + document.getId()); ReferenceDocument referenceDocument = saveFile(req, document); JsonCommandServlet.writeResponse(resp, FlatJsonExporter.of(referenceDocument)); return null; } }); } else { resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); } } catch (FileUploadException e) { log.severe(e); throw new ServletException(e); } catch (Exception e) { log.severe(e); throw new ServletException(e); } }
From source file:com.flipkart.poseidon.core.PoseidonServlet.java
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); }//from w w w.j a v a 2 s. co m // 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); } } }
From source file:edu.emory.cci.aiw.cvrg.eureka.servlet.JobSubmitServlet.java
private Long submitJob(HttpServletRequest request, Principal principal) throws FileUploadException, IOException, ClientException, ParseException { DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); /*/*w w w. jav a2s . c o m*/ *Set the size threshold, above which content will be stored on disk. */ fileItemFactory.setSizeThreshold(5 * 1024 * 1024); //5 MB /* * Set the temporary directory to store the uploaded files of size above threshold. */ fileItemFactory.setRepository(this.tmpDir); ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory); /* * Parse the request */ List items = uploadHandler.parseRequest(request); Properties fields = new Properties(); for (Iterator itr = items.iterator(); itr.hasNext();) { FileItem item = (FileItem) itr.next(); /* * Handle Form Fields. */ if (item.isFormField()) { fields.setProperty(item.getFieldName(), item.getString()); } } JobSpec jobSpec = MAPPER.readValue(fields.getProperty("jobSpec"), JobSpec.class); for (Iterator itr = items.iterator(); itr.hasNext();) { FileItem item = (FileItem) itr.next(); if (!item.isFormField()) { //Handle Uploaded files. log("Spreadsheet upload for user " + principal.getName() + ": Field Name = " + item.getFieldName() + ", File Name = " + item.getName() + ", Content type = " + item.getContentType() + ", File Size = " + item.getSize()); if (item.getSize() > 0) { InputStream is = item.getInputStream(); try { this.servicesClient.upload(FilenameUtils.getName(item.getName()), jobSpec.getSourceConfigId(), item.getFieldName(), is); log("File '" + item.getName() + "' uploaded successfully"); } finally { if (is != null) { try { is.close(); } catch (IOException ignore) { } } } } else { log("File '" + item.getName() + "' ignored because it was zero length"); } } } URI uri = this.servicesClient.submitJob(jobSpec); String uriStr = uri.toString(); Long jobId = Long.valueOf(uriStr.substring(uriStr.lastIndexOf("/") + 1)); log("Job " + jobId + " submitted for user " + principal.getName()); return jobId; }
From source file:com.hightern.fckeditor.connector.Dispatcher.java
/** * Called by the connector servlet to handle a {@code POST} request. In particular, it handles the {@link Command#FILE_UPLOAD FileUpload} and {@link Command#QUICK_UPLOAD QuickUpload} commands. * //from w w w . j a va2 s .co m * @param request * the current request instance * @return the upload response instance associated with this request */ @SuppressWarnings("unchecked") UploadResponse doPost(final HttpServletRequest request) { Dispatcher.logger.debug("Entering Dispatcher#doPost"); final Context context = ThreadLocalData.getContext(); context.logBaseParameters(); UploadResponse uploadResponse = null; // check permissions for user actions if (!RequestCycleHandler.isFileUploadEnabled(request)) { uploadResponse = UploadResponse.getFileUploadDisabledError(); } else if (!Command.isValidForPost(context.getCommandStr())) { uploadResponse = UploadResponse.getInvalidCommandError(); } else if (!ResourceType.isValidType(context.getTypeStr())) { uploadResponse = UploadResponse.getInvalidResourceTypeError(); } else if (!UtilsFile.isValidPath(context.getCurrentFolderStr())) { uploadResponse = UploadResponse.getInvalidCurrentFolderError(); } else { // call the Connector#fileUpload final ResourceType type = context.getDefaultResourceType(); final FileItemFactory factory = new DiskFileItemFactory(); final ServletFileUpload upload = new ServletFileUpload(factory); try { final List<FileItem> items = upload.parseRequest(request); // We upload just one file at the same time final FileItem uplFile = items.get(0); // Some browsers transfer the entire source path not just the // filename final String fileName = FilenameUtils.getName(uplFile.getName()); Dispatcher.logger.debug("Parameter NewFile: {}", fileName); // check the extension if (type.isDeniedExtension(FilenameUtils.getExtension(fileName))) { uploadResponse = UploadResponse.getInvalidFileTypeError(); } else if (type.equals(ResourceType.IMAGE) && PropertiesLoader.isSecureImageUploads() && !UtilsFile.isImage(uplFile.getInputStream())) { uploadResponse = UploadResponse.getInvalidFileTypeError(); } else { final String sanitizedFileName = UtilsFile.sanitizeFileName(fileName); Dispatcher.logger.debug("Parameter NewFile (sanitized): {}", sanitizedFileName); final String newFileName = connector.fileUpload(type, context.getCurrentFolderStr(), sanitizedFileName, uplFile.getInputStream()); final String fileUrl = UtilsResponse.fileUrl(RequestCycleHandler.getUserFilesPath(request), type, context.getCurrentFolderStr(), newFileName); if (sanitizedFileName.equals(newFileName)) { uploadResponse = UploadResponse.getOK(fileUrl); } else { uploadResponse = UploadResponse.getFileRenamedWarning(fileUrl, newFileName); Dispatcher.logger.debug("Parameter NewFile (renamed): {}", newFileName); } } uplFile.delete(); } catch (final InvalidCurrentFolderException e) { uploadResponse = UploadResponse.getInvalidCurrentFolderError(); } catch (final WriteException e) { uploadResponse = UploadResponse.getFileUploadWriteError(); } catch (final IOException e) { uploadResponse = UploadResponse.getFileUploadWriteError(); } catch (final FileUploadException e) { uploadResponse = UploadResponse.getFileUploadWriteError(); } } Dispatcher.logger.debug("Exiting Dispatcher#doPost"); return uploadResponse; }
From source file:com.ephesoft.gxt.uploadbatch.server.UploadBatchImageServlet.java
private void uploadFile(HttpServletRequest req, HttpServletResponse resp, BatchSchemaService batchSchemaService, String currentBatchUploadFolderName) throws IOException { PrintWriter printWriter = resp.getWriter(); File tempFile = null;// ww w . j a va 2s . c o m InputStream instream = null; OutputStream out = null; String uploadBatchFolderPath = batchSchemaService.getUploadBatchFolder(); String uploadFileName = ""; if (ServletFileUpload.isMultipartContent(req)) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); uploadFileName = ""; String uploadFilePath = ""; List<FileItem> items; try { items = upload.parseRequest(req); for (FileItem item : items) { if (!item.isFormField()) { // && "uploadFile".equals(item.getFieldName())) { uploadFileName = item.getName(); if (uploadFileName != null) { uploadFileName = uploadFileName .substring(uploadFileName.lastIndexOf(File.separator) + 1); } uploadFilePath = uploadBatchFolderPath + File.separator + currentBatchUploadFolderName + File.separator + uploadFileName; try { instream = item.getInputStream(); tempFile = new File(uploadFilePath); out = new FileOutputStream(tempFile); byte buf[] = new byte[1024]; int len; while ((len = instream.read(buf)) > 0) { out.write(buf, 0, len); } } catch (FileNotFoundException e) { log.error("Unable to create the upload folder." + e, e); printWriter.write("Unable to create the upload folder.Please try again."); tempFile.delete(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "unable to upload. please see server logs for more details."); } catch (IOException e) { log.error("Unable to read the file." + e, e); printWriter.write("Unable to read the file.Please try again."); tempFile.delete(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "unable to upload. please see server logs for more details."); } finally { if (out != null) { out.close(); } if (instream != null) { instream.close(); } } } } } catch (FileUploadException e) { log.error("Unable to read the form contents." + e, e); printWriter.write("Unable to read the form contents.Please try again."); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "unable to upload. please see server logs for more details."); } } else { log.error("Request contents type is not supported."); printWriter.write("Request contents type is not supported."); } printWriter.write("currentBatchUploadFolderName:" + currentBatchUploadFolderName); printWriter.append("|"); printWriter.append("fileName:").append(uploadFileName); printWriter.append("|"); printWriter.flush(); }