List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload setSizeMax
public void setSizeMax(long sizeMax)
From source file:com.pronoiahealth.olhie.server.rest.BookAssetUploadServiceImpl.java
/** * Receive an upload book assest// w ww . ja v a 2 s . c o m * * @see com.pronoiahealth.olhie.server.rest.BookAssetUploadService#process2(javax.servlet.http.HttpServletRequest) */ @Override @POST @Path("/upload2") @Produces("text/html") @SecureAccess({ SecurityRoleEnum.ADMIN, SecurityRoleEnum.AUTHOR }) public String process2(@Context HttpServletRequest req) throws ServletException, IOException, FileUploadException { try { // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(req); if (isMultipart == true) { // FileItemFactory fileItemFactory = new FileItemFactory(); String description = null; String descriptionDetail = null; String hoursOfWorkStr = null; String bookId = null; String action = null; String dataType = null; String contentType = null; //String data = null; byte[] bytes = null; String fileName = null; long size = 0; ServletFileUpload fileUpload = new ServletFileUpload(); fileUpload.setSizeMax(FILE_SIZE_LIMIT); FileItemIterator iter = fileUpload.getItemIterator(req); while (iter.hasNext()) { FileItemStream item = iter.next(); InputStream stream = item.openStream(); if (item.isFormField()) { // description if (item.getFieldName().equals("description")) { description = Streams.asString(stream); } // detail if (item.getFieldName().equals("descriptionDetail")) { descriptionDetail = Streams.asString(stream); } // Work hours if (item.getFieldName().equals("hoursOfWork")) { hoursOfWorkStr = Streams.asString(stream); } // BookId if (item.getFieldName().equals("bookId")) { bookId = Streams.asString(stream); } // action if (item.getFieldName().equals("action")) { action = Streams.asString(stream); } // datatype if (item.getFieldName().equals("dataType")) { dataType = Streams.asString(stream); } } else { if (item != null) { contentType = item.getContentType(); fileName = item.getName(); item.openStream(); InputStream in = item.openStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copy(in, bos); bytes = bos.toByteArray(); size = bytes.length; } } } // convert the hoursOfWork int hoursOfWork = 0; if (hoursOfWorkStr != null) { try { hoursOfWork = Integer.parseInt(hoursOfWorkStr); } catch (Exception e) { log.log(Level.WARNING, "Could not conver " + hoursOfWorkStr + " to an int in BookAssetUploadServiceImpl. Converting to 0."); hoursOfWork = 0; } } // Verify that the session user is the author or co-author of // the book. They would be the only ones who could add to the // book. String userId = userToken.getUserId(); boolean isAuthor = bookDAO.isUserAuthorOrCoauthorOfBook(userId, bookId); if (isAuthor == false) { throw new Exception("The user " + userId + " is not the author or co-author of the book."); } // Add to the database bookDAO.addUpdateBookassetBytes(description, descriptionDetail, bookId, contentType, BookAssetDataType.valueOf(dataType).toString(), bytes, action, fileName, null, null, size, hoursOfWork, userId); // Tell Solr about the update queueBookEvent.fire(new QueueBookEvent(bookId, userId)); } return "OK"; } catch (Exception e) { log.log(Level.SEVERE, "Throwing servlet exception for unhandled exception", e); // return "ERROR:\n" + e.getMessage(); if (e instanceof FileUploadException) { throw (FileUploadException) e; } else { throw new FileUploadException(e.getMessage()); } } }
From source file:com.food.adminservlet.FoodServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int foodid = 0; String foodName = ""; String fooddesc = ""; Double foodprice = 0.0;//from w w w . j a v a 2s. c o m String foodCategory = ""; PrintWriter out = response.getWriter(); isMultipart = ServletFileUpload.isMultipartContent(request); FoodBean bkfood = new FoodBean(); FoodBL foodbl = new FoodBL(); try { response.setContentType("text/html"); //java.io.PrintWriter out = response.getWriter( ); DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory factory.setSizeThreshold(maxMemSize); // Location to save data that is larger than maxMemSize. factory.setRepository(new File("c:\\temp")); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax(maxFileSize); // Parse the request to get file items. List fileItems = upload.parseRequest(request); // Process the uploaded file items Iterator i = fileItems.iterator(); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet upload</title>"); out.println("</head>"); out.println("<body>"); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (fi.isFormField()) { if (fi.getFieldName().equals("foodid")) { foodid = Integer.parseInt(fi.getString()); } if (fi.getFieldName().equals("foodname")) { foodName = fi.getString(); } if (fi.getFieldName().equals("fooddesc")) { fooddesc = fi.getString(); } if (fi.getFieldName().equals("foodprice")) { foodprice = Double.parseDouble(fi.getString()); } if (fi.getFieldName().equals("foodcate")) { foodCategory = fi.getString(); } out.println("<br>"); } if (!fi.isFormField()) { // Get the uploaded file parameters String fieldName = fi.getFieldName(); fileName = fi.getName(); String contentType = fi.getContentType(); boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); // Write the file if (fileName.lastIndexOf("\\") >= 0) { file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\"))); } else { file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1)); } fi.write(file); out.println("Uploaded Filename: " + fileName + "<br>"); } } out.println(fileName); bkfood.setFoodId(foodid); bkfood.setFoodName(foodName); bkfood.setFoodPrice(foodprice); bkfood.setFoodCateg(foodCategory); bkfood.setFoodDesc(fooddesc); bkfood.setFoodRetreiveImage(fileName); // bkfood.setFoodimage(request.getPart("foodimage")); bkfood.setFoodstatus("Y"); int chk = foodbl.addFoodItems(bkfood); out.println(chk); if (chk == 1) { response.sendRedirect("food.jsp"); } } catch (Exception ex) { out.println(ex); } }
From source file:com.siberhus.web.ckeditor.servlet.MultipartServletRequest.java
public MultipartServletRequest(HttpServletRequest request) throws FileUploadException { super(request); // if(!"POST".equals(request.getMethod())){ // return; // }/* ww w . j ava2 s . c o m*/ CkeditorConfig config = CkeditorConfigurationHolder.config(); // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Set factory constraints if (config.fileupload().sizeThreshold() != null) { factory.setSizeThreshold(config.fileupload().sizeThreshold()); } if (config.fileupload().repository() != null) { factory.setRepository(config.fileupload().repository()); } // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Set overall request size constraint if (config.fileupload().sizeMax() != null) { upload.setSizeMax(config.fileupload().sizeMax()); } if (config.fileupload().fileSizeMax() != null) { upload.setFileSizeMax(config.fileupload().fileSizeMax()); } // Copy params from query string Enumeration<String> paramNames = request.getParameterNames(); while (paramNames.hasMoreElements()) { String paramName = paramNames.nextElement(); String paramValues[] = request.getParameterValues(paramName); if (paramValues != null) { this.paramMap.put(paramName, Literal.list(paramValues)); } } @SuppressWarnings("unchecked") List<FileItem> itemList = upload.parseRequest(request); for (FileItem item : itemList) { String fieldName = item.getFieldName(); if (item.isFormField()) { List<String> values = paramMap.get(fieldName); if (values == null) { paramMap.put(fieldName, Literal.list(item.getString())); } else { values.add(item.getString()); } } else { fileItemMap.put(fieldName, item); fileItems.add(item); } } }
From source file:com.controller.RecipeImage.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w w w . j a v a 2s . c o m*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); //retrieving the path to store image from web.xml filePath = getServletContext().getInitParameter("recipeImageStorePath"); //retrieving the path to display image from web.xml fileDisplay = getServletContext().getInitParameter("recipeImageDisplayPath"); // Check that we have a file upload request isMultipart = ServletFileUpload.isMultipartContent(request); response.setContentType("text/html"); java.io.PrintWriter out = response.getWriter(); if (!isMultipart) { out.println("<html>"); out.println("<head>"); out.println("<title>Servlet upload</title>"); out.println("</head>"); out.println("<body>"); out.println("<p>No file uploaded</p>"); out.println("</body>"); out.println("</html>"); return; } DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory factory.setSizeThreshold(maxMemSize); // Location to save data that is larger than maxMemSize. factory.setRepository(new File("c:\\temp")); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax(maxFileSize); try { // Parse the request to get file items. List fileItems = upload.parseRequest(request); // Process the uploaded file items Iterator i = fileItems.iterator(); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet upload</title>"); out.println("</head>"); out.println("<body>"); out.println("1"); while (i.hasNext()) { out.println("2"); FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { // Get the uploaded file parameters String fieldName = fi.getFieldName(); fileName = fi.getName(); fileName = randomString(fileName); String contentType = fi.getContentType(); boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); // Write the file if (fileName.lastIndexOf("\\") >= 0) { file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\"))); } else { file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1)); } fi.write(file); out.println("Uploaded Filename: " + fileName + "<br>" + filePath); } else { out.println("No file"); } } out.println("</body>"); out.println("</html>"); RecipeBean recipeBean = new RecipeBean(); RecipeDAO recipeDAO = new RecipeDAO(); String image = fileDisplay + "" + fileName; out.println(image); HttpSession session = request.getSession(); String recipeId = (String) session.getAttribute("recipeId"); session.removeAttribute("recipeId"); recipeDAO.addImage(recipeId, image); response.sendRedirect("Home"); } catch (Exception ex) { System.out.println(ex); } }
From source file:com.mycompany.mytubeaws.UploadServlet.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request//from w w w . j a v a 2s . c o m * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String result = ""; String fileName = null; boolean uploaded = false; // configures upload settings DiskFileItemFactory factory = new DiskFileItemFactory(); // sets memory threshold - beyond which files are stored in disk factory.setSizeThreshold(1024 * 1024 * 3); // 3mb factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); // sets temporary location to store files ServletFileUpload upload = new ServletFileUpload(factory); upload.setFileSizeMax(1024 * 1024 * 40); // sets maximum size of upload file upload.setSizeMax(1024 * 1024 * 50); // sets maximum size of request (include file + form data) try { List<FileItem> formItems = upload.parseRequest(request); // parses the request's content to extract file data if (formItems != null && formItems.size() > 0) // iterates over form's fields { for (FileItem item : formItems) // processes only fields that are not form fields { if (!item.isFormField()) { fileName = item.getName(); UUID id = UUID.randomUUID(); fileName = FilenameUtils.getBaseName(fileName) + "_ID-" + id.toString() + "." + FilenameUtils.getExtension(fileName); File file = File.createTempFile("aws-java-sdk-upload", ""); item.write(file); // write form item to file (?) if (file.length() == 0) throw new RuntimeException("No file selected or empty file uploaded."); try { s3.putObject(new PutObjectRequest(bucketName, fileName, file)); result += "File uploaded successfully; "; uploaded = true; } catch (AmazonServiceException ase) { System.out.println("Caught an AmazonServiceException, which means your request made it " + "to Amazon S3, but was rejected with an error response for some reason."); System.out.println("Error Message: " + ase.getMessage()); System.out.println("HTTP Status Code: " + ase.getStatusCode()); System.out.println("AWS Error Code: " + ase.getErrorCode()); System.out.println("Error Type: " + ase.getErrorType()); System.out.println("Request ID: " + ase.getRequestId()); result += "AmazonServiceException thrown; "; } catch (AmazonClientException ace) { System.out .println("Caught an AmazonClientException, which means the client encountered " + "a serious internal problem while trying to communicate with S3, " + "such as not being able to access the network."); System.out.println("Error Message: " + ace.getMessage()); result += "AmazonClientException thrown; "; } file.delete(); } } } } catch (Exception ex) { result += "Generic exception: '" + ex.getMessage() + "'; "; ex.printStackTrace(); } if (fileName != null && uploaded) result += "Generated file ID: " + fileName; System.out.println(result); request.setAttribute("resultText", result); request.getRequestDispatcher("/UploadResult.jsp").forward(request, response); }
From source file:com.google.phonenumbers.PhoneNumberParserServlet.java
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { String phoneNumber = null;// w w w . ja v a 2s. com String defaultCountry = null; String languageCode = "en"; // Default languageCode to English if nothing is entered. String regionCode = ""; String fileContents = null; ServletFileUpload upload = new ServletFileUpload(); upload.setSizeMax(50000); try { FileItemIterator iterator = upload.getItemIterator(req); while (iterator.hasNext()) { FileItemStream item = iterator.next(); InputStream in = item.openStream(); if (item.isFormField()) { String fieldName = item.getFieldName(); if (fieldName.equals("phoneNumber")) { phoneNumber = Streams.asString(in, "UTF-8"); } else if (fieldName.equals("defaultCountry")) { defaultCountry = Streams.asString(in).toUpperCase(); } else if (fieldName.equals("languageCode")) { String languageEntered = Streams.asString(in).toLowerCase(); if (languageEntered.length() > 0) { languageCode = languageEntered; } } else if (fieldName.equals("regionCode")) { regionCode = Streams.asString(in).toUpperCase(); } } else { try { fileContents = IOUtils.toString(in); } finally { IOUtils.closeQuietly(in); } } } } catch (FileUploadException e1) { e1.printStackTrace(); } StringBuilder output; if (fileContents.length() == 0) { output = getOutputForSingleNumber(phoneNumber, defaultCountry, languageCode, regionCode); resp.setContentType("text/html"); resp.setCharacterEncoding("UTF-8"); resp.getWriter().println("<html><head>"); resp.getWriter() .println("<link type=\"text/css\" rel=\"stylesheet\" href=\"/stylesheets/main.css\" />"); resp.getWriter().println("</head>"); resp.getWriter().println("<body>"); resp.getWriter().println("Phone Number entered: " + phoneNumber + "<br>"); resp.getWriter().println("defaultCountry entered: " + defaultCountry + "<br>"); resp.getWriter().println("Language entered: " + languageCode + (regionCode.length() == 0 ? "" : " (" + regionCode + ")" + "<br>")); } else { output = getOutputForFile(defaultCountry, fileContents); resp.setContentType("text/html"); } resp.getWriter().println(output); resp.getWriter().println("</body></html>"); }
From source file:graphvis.webui.servlets.UploadServlet.java
/** * This method receives POST from the index.jsp page and uploads file, * converts into the correct format then places in the HDFS. *//*from ww w . ja v a2 s . co m*/ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) { response.setStatus(403); return; } File tempDirFileObject = new File(Configuration.tempDirectory); // Create/remove temp folder if (tempDirFileObject.exists()) { FileUtils.deleteDirectory(tempDirFileObject); } // (Re-)create temp directory tempDirFileObject.mkdir(); FileUtils.copyFile( new File(getServletContext() .getRealPath("giraph-1.1.0-SNAPSHOT-for-hadoop-2.2.0-jar-with-dependencies.jar")), new File(Configuration.tempDirectory + "/giraph-1.1.0-SNAPSHOT-for-hadoop-2.2.0-jar-with-dependencies.jar")); FileUtils.copyFile(new File(getServletContext().getRealPath("dist-graphvis.jar")), new File(Configuration.tempDirectory + "/dist-graphvis.jar")); // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Sets the size threshold beyond which files are written directly to // disk. factory.setSizeThreshold(Configuration.MAX_MEMORY_SIZE); // Sets the directory used to temporarily store files that are larger // than the configured size threshold. We use temporary directory for // java factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Set overall request size constraint upload.setSizeMax(Configuration.MAX_REQUEST_SIZE); String fileName = ""; try { // Parse the request List<?> items = upload.parseRequest(request); Iterator<?> iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { fileName = new File(item.getName()).getName(); String filePath = Configuration.tempDirectory + File.separator + fileName; File uploadedFile = new File(filePath); System.out.println(filePath); // saves the file to upload directory try { item.write(uploadedFile); } catch (Exception ex) { throw new ServletException(ex); } } } String fullFilePath = Configuration.tempDirectory + File.separator + fileName; String extension = FilenameUtils.getExtension(fullFilePath); // Load Files intoHDFS // (This is where we do the parsing.) loadIntoHDFS(fullFilePath, extension); getServletContext().setAttribute("fileName", new File(fullFilePath).getName()); getServletContext().setAttribute("fileExtension", extension); // Displays fileUploaded.jsp page after upload finished getServletContext().getRequestDispatcher("/fileUploaded.jsp").forward(request, response); } catch (FileUploadException ex) { throw new ServletException(ex); } }
From source file:com.controller.UploadLogo.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from www. j a v a 2s .co m * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { super.processRequest(request, response); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); getSqlMethodsInstance().session = request.getSession(); String filePath = null; String fileName = null, fieldName = null, uploadPath = null, uploadType = null; RequestDispatcher request_dispatcher = null; File file; int maxFileSize = 5000 * 1024; int maxMemSize = 5000 * 1024; try { uploadPath = AppConstants.USER_LOGO; // Verify the content type String contentType = request.getContentType(); if ((contentType.indexOf("multipart/form-data") >= 0)) { DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory factory.setSizeThreshold(maxMemSize); // Location to save data that is larger than maxMemSize. factory.setRepository(new File(AppConstants.TMP_FOLDER)); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax(maxFileSize); // Parse the request to get file items. List fileItems = upload.parseRequest(request); // Process the uploaded file items Iterator i = fileItems.iterator(); out.println("<html>"); out.println("<head>"); out.println("<title>JSP File upload</title>"); out.println("</head>"); out.println("<body>"); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); boolean ch = fi.isFormField(); if (!fi.isFormField()) { // Get the uploaded file parameters fieldName = fi.getFieldName(); fileName = fi.getName(); String uid = (String) getSqlMethodsInstance().session.getAttribute("EmailID"); int UID = getSqlMethodsInstance().getUserID(uid); uploadPath = uploadPath + File.separator + UID + File.separator + "logo"; File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdirs(); } // int inStr = fileName.indexOf("."); // String Str = fileName.substring(0, inStr); // // fileName = Str + "_" + UID + ".jpeg"; fileName = fileName + "_" + UID; getSqlMethodsInstance().session.setAttribute("UID", UID); getSqlMethodsInstance().session.setAttribute("ImageFileName", fileName); boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); filePath = uploadPath + File.separator + fileName; File storeFile = new File(filePath); fi.write(storeFile); getSqlMethodsInstance().updateUsers(UID, fileName); out.println("Uploaded Filename: " + filePath + "<br>"); } } } } catch (Exception ex) { logger.log(Level.SEVERE, util.Utility.logMessage(ex, "Exception while updating org name:", getSqlMethodsInstance().error)); out.println(getSqlMethodsInstance().error); } finally { out.close(); getSqlMethodsInstance().closeConnection(); } }
From source file:com.oprisnik.semdroid.SemdroidServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.info("doPost"); StringBuilder sb = new StringBuilder(); try {/*from ww w . ja v a 2 s.c om*/ ServletFileUpload upload = new ServletFileUpload(); // set max size (-1 for unlimited size) upload.setSizeMax(1024 * 1024 * 30); // 30MB upload.setHeaderEncoding("UTF-8"); FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); if (item.isFormField()) { // Process regular form fields // String fieldname = item.getFieldName(); // String fieldvalue = item.getString(); // log.info("Got form field: " + fieldname + " " + fieldvalue); } else { // Process form file field (input type="file"). String fieldname = item.getFieldName(); String filename = FilenameUtils.getBaseName(item.getName()); log.info("Got file: " + filename); InputStream filecontent = null; try { filecontent = item.openStream(); // analyze String txt = analyzeApk(filecontent); if (txt != null) { sb.append(txt); } else { sb.append("Error. Could not analyze ").append(filename); } log.info("Analysis done!"); } finally { if (filecontent != null) { filecontent.close(); } } } } response.getWriter().print(sb.toString()); } catch (FileUploadException e) { throw new ServletException("Cannot parse multipart request.", e); } catch (Exception ex) { log.warning("Exception: " + ex.getMessage()); log.throwing(this.getClass().getName(), "doPost", ex); } }
From source file:bijian.util.upload.MyMultiPartRequest.java
private List<FileItem> parseRequest(HttpServletRequest servletRequest, String saveDir) throws FileUploadException { DiskFileItemFactory fac = createDiskFileItemFactory(saveDir); ServletFileUpload upload = new ServletFileUpload(fac); upload.setSizeMax(maxSize); FileUploadListener myFileUploadListener = new FileUploadListener(servletRequest); upload.setProgressListener(myFileUploadListener); return upload.parseRequest(createRequestContext(servletRequest)); }