List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload setSizeMax
public void setSizeMax(long sizeMax)
From source file:controller.productServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); String proimage = ""; String nameProduct = ""; double priceProduct = 0; String desProduct = ""; String colorProduct = ""; int years = 0; int catId = 0; int proid = 0; String command = ""; if (!ServletFileUpload.isMultipartContent(request)) { // if not, we stop here PrintWriter writer = response.getWriter(); writer.println("Error: Form must has enctype=multipart/form-data."); writer.flush();// ww w . j a va2s.co m return; } // configures upload settings DiskFileItemFactory factory = new DiskFileItemFactory(); // sets memory threshold - beyond which files are stored in disk factory.setSizeThreshold(MEMORY_THRESHOLD); // sets temporary location to store files factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload upload = new ServletFileUpload(factory); // sets maximum size of upload file upload.setFileSizeMax(MAX_FILE_SIZE); // sets maximum size of request (include file + form data) upload.setSizeMax(MAX_REQUEST_SIZE); // constructs the directory path to store upload file // this path is relative to application's directory String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY; // creates the directory if it does not exist File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdir(); } try { // parses the request's content to extract file data @SuppressWarnings("unchecked") List<FileItem> formItems = upload.parseRequest(request); 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()) { proimage = new File(item.getName()).getName(); String filePath = uploadPath + File.separator + proimage; File storeFile = new File(filePath); System.out.println(proimage); item.write(storeFile); } else if (item.getFieldName().equals("name")) { nameProduct = item.getString(); } else if (item.getFieldName().equals("price")) { priceProduct = Double.parseDouble(item.getString()); } else if (item.getFieldName().equals("description")) { desProduct = item.getString(); System.out.println(desProduct); } else if (item.getFieldName().equals("color")) { colorProduct = item.getString(); } else if (item.getFieldName().equals("years")) { years = Integer.parseInt(item.getString()); } else if (item.getFieldName().equals("catogory_name")) { catId = Integer.parseInt(item.getString()); } else if (item.getFieldName().equals("command")) { command = item.getString(); } else if (item.getFieldName().equals("proid")) { proid = Integer.parseInt(item.getString()); } } } } catch (Exception ex) { request.setAttribute("message", "There was an error: " + ex.getMessage()); } String url = "", error = ""; if (nameProduct.equals("")) { error = "Vui lng nhp tn danh mc!"; request.setAttribute("error", error); } try { if (error.length() == 0) { ProductEntity p = new ProductEntity(catId, nameProduct, priceProduct, proimage, desProduct, colorProduct, years); switch (command) { case "insert": prod.insertProduct(p); url = "/java/admin/ql-product.jsp"; break; case "update": prod.updateProduct(catId, nameProduct, priceProduct, proimage, desProduct, colorProduct, years, proid); url = "/java/admin/ql-product.jsp"; break; } } else { url = "/java/admin/add-product.jsp"; } } catch (Exception e) { } response.sendRedirect(url); }
From source file:com.ultrapower.eoms.common.plugin.ajaxupload.AjaxMultiPartRequest.java
/** * Creates a new request wrapper to handle multi-part data using methods * adapted from Jason Pell's multipart classes (see class description). * /* w w w .java2 s .com*/ * @param saveDir * the directory to save off the file * @param servletRequest * the request containing the multipart * @throws java.io.IOException * is thrown if encoding fails. * @throws */ public void parse(HttpServletRequest servletRequest, String saveDir) throws IOException { Integer delay = 3; UploadListener listener = null; DiskFileItemFactory fac = null; // Parse the request try { if (maxSize >= 0L && servletRequest.getContentLength() > maxSize) { servletRequest.setAttribute("error", "size"); FileItemIterator it = new ServletFileUpload(fac).getItemIterator(servletRequest); // handle with each file: while (it.hasNext()) { FileItemStream item = it.next(); if (item.isFormField()) { List<String> values; if (params.get(item.getFieldName()) != null) { values = params.get(item.getFieldName()); } else { values = new ArrayList<String>(); } InputStream stream = item.openStream(); values.add(Streams.asString(stream)); params.put(item.getFieldName(), values); } } return; } else { listener = new UploadListener(servletRequest, delay); fac = new MonitoredDiskFileItemFactory(listener); } // Make sure that the data is written to file fac.setSizeThreshold(0); if (saveDir != null) { fac.setRepository(new File(saveDir)); } ServletFileUpload upload = new ServletFileUpload(fac); upload.setSizeMax(maxSize); List items = upload.parseRequest(createRequestContext(servletRequest)); for (Object item1 : items) { FileItem item = (FileItem) item1; if (log.isDebugEnabled()) log.debug("Found item " + item.getFieldName()); if (item.isFormField()) { log.debug("Item is a normal form field"); List<String> values; if (params.get(item.getFieldName()) != null) { values = params.get(item.getFieldName()); } else { values = new ArrayList<String>(); } String charset = servletRequest.getCharacterEncoding(); if (charset != null) { values.add(item.getString(charset)); } else { values.add(item.getString()); } params.put(item.getFieldName(), values); } else { log.debug("Item is a file upload"); // Skip file uploads that don't have a file name - meaning // that no file was selected. if (item.getName() == null || item.getName().trim().length() < 1) { log.debug("No file has been uploaded for the field: " + item.getFieldName()); continue; } String targetFileName = item.getName(); if (!targetFileName.contains(":")) item.write(new File(targetDirectory + targetFileName)); //?Action List<FileItem> values; if (files.get(item.getFieldName()) != null) { values = files.get(item.getFieldName()); } else { values = new ArrayList<FileItem>(); } values.add(item); files.put(item.getFieldName(), values); } } } catch (Exception e) { log.error(e); errors.add(e.getMessage()); } }
From source file:controller.categoryServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); String catimage = ""; String nameCategory = ""; String command = ""; int catogory_id = 0; String catogory_imagehidden = ""; String catogory_image = ""; if (!ServletFileUpload.isMultipartContent(request)) { // if not, we stop here PrintWriter writer = response.getWriter(); writer.println("Error: Form must has enctype=multipart/form-data."); writer.flush();/*w ww . ja va2 s . c o m*/ return; } // configures upload settings DiskFileItemFactory factory = new DiskFileItemFactory(); // sets memory threshold - beyond which files are stored in disk factory.setSizeThreshold(MEMORY_THRESHOLD); // sets temporary location to store files factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload upload = new ServletFileUpload(factory); // sets maximum size of upload file upload.setFileSizeMax(MAX_FILE_SIZE); // sets maximum size of request (include file + form data) upload.setSizeMax(MAX_REQUEST_SIZE); // constructs the directory path to store upload file // this path is relative to application's directory String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY; // creates the directory if it does not exist File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdir(); } try { // parses the request's content to extract file data @SuppressWarnings("unchecked") List<FileItem> formItems = upload.parseRequest(request); 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()) { catimage = new File(item.getName()).getName(); String filePath = uploadPath + File.separator + catimage; File storeFile = new File(filePath); item.write(storeFile); } else if (item.getFieldName().equals("name")) { nameCategory = item.getString(); } else if (item.getFieldName().equals("command")) { command = item.getString(); } else if (item.getFieldName().equals("catid")) { catogory_id = Integer.parseInt(item.getString()); } else if (item.getFieldName().equals("catogery_imagehidden")) { catogory_imagehidden = item.getString(); } } } } catch (Exception ex) { request.setAttribute("message", "There was an error: " + ex.getMessage()); } String url = "", error = ""; if (nameCategory.equals("")) { error = "Vui lng nhp tn danh mc!"; request.setAttribute("error", error); } HttpSession session = request.getSession(); try { if (error.length() == 0) { CategoryEntity c = new CategoryEntity(nameCategory, catimage); switch (command) { case "insert": if (cate.getListCategoryByName(nameCategory).size() > 0) { System.out.println("ten k "); out.println("ten k dc trung nhau"); out.flush(); return; } else { cate.insertCategory(c); request.setAttribute("er", "thanh cong"); url = "/java/admin/ql-category.jsp"; } break; case "update": if (cate.getListCategoryByName(nameCategory).size() > 0) { System.out.println("ten k "); out.println("ten k dc trung nhau"); out.flush(); return; } else { cate.updateCategory(nameCategory, catimage, catogory_id); url = "/java/admin/ql-category.jsp"; } break; } } else { url = "/java/admin/add-category.jsp"; } } catch (Exception e) { } response.sendRedirect(url); }
From source file:com.glaf.base.utils.upload.FileUploadBackGroundServlet.java
/** * ?//ww w . ja v a2 s . c o m */ private void processFileUpload(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String serviceKey = request.getParameter("serviceKey"); if (serviceKey == null) { serviceKey = "global"; } int maxUploadSize = conf.getInt(serviceKey + ".maxUploadSize", 0); if (maxUploadSize == 0) { maxUploadSize = conf.getInt("upload.maxUploadSize", 10);// 10MB } maxUploadSize = maxUploadSize * FileUtils.MB_SIZE; DiskFileItemFactory factory = new DiskFileItemFactory(); // ? factory.setSizeThreshold(204800); File tempDir = new File(getUploadDir() + "/temp"); if (!tempDir.exists()) { tempDir.mkdir(); } // ? factory.setRepository(tempDir); ServletFileUpload upload = new ServletFileUpload(factory); // ? upload.setFileSizeMax(maxUploadSize); // request upload.setSizeMax(maxUploadSize); upload.setProgressListener(new FileUploadListener(request)); upload.setHeaderEncoding("UTF-8"); // ???FileUploadStatus Bean FileMgmtFactory.saveStatusBean(request, initStatusBean(request)); try { List<?> items = upload.parseRequest(request); // url for (int i = 0; i < items.size(); i++) { FileItem item = (FileItem) items.get(i); if (item.isFormField()) { break; } } // String uploadDir = com.glaf.base.utils.StringUtil.createDir(getUploadDir()); // ? for (int i = 0; i < items.size(); i++) { FileItem item = (FileItem) items.get(i); // ? if (FileMgmtFactory.getStatusBean(request).getCancel()) { deleteUploadedFile(request); break; } else if (!item.isFormField() && item.getName().length() > 0) { logger.debug("" + item.getName()); // ? String fileId = UUID32.getUUID(); String path = uploadDir + FileUtils.sp + fileId; File uploadedFile = new File(new File(getUploadDir(), uploadDir), fileId); item.write(uploadedFile); // FileUploadStatus satusBean = FileMgmtFactory.getStatusBean(request); FileInfo fileInfo = new FileInfo(); fileInfo.setCreateDate(new Date()); fileInfo.setFileId(fileId); fileInfo.setFile(uploadedFile); fileInfo.setFilename(FileUtils.getFilename(item.getName())); fileInfo.setSize(item.getSize()); fileInfo.setPath(path); satusBean.getUploadFileUrlList().add(fileInfo); FileMgmtFactory.saveStatusBean(request, satusBean); Thread.sleep(500); } } } catch (FileUploadException ex) { uploadExceptionHandle(request, "?:" + ex.getMessage()); } catch (Exception ex) { uploadExceptionHandle(request, "??:" + ex.getMessage()); } String forwardURL = request.getParameter("forwardURL"); if (StringUtils.isEmpty(forwardURL)) { forwardURL = "/others/attachment.do?method=showResult"; } request.getRequestDispatcher(forwardURL).forward(request, response); }
From source file:com.niconico.mylasta.direction.sponsor.NiconicoMultipartRequestHandler.java
protected ServletFileUpload createServletFileUpload(HttpServletRequest request) { final DiskFileItemFactory fileItemFactory = createDiskFileItemFactory(); final ServletFileUpload upload = newServletFileUpload(fileItemFactory); upload.setHeaderEncoding(request.getCharacterEncoding()); upload.setSizeMax(getSizeMax()); return upload; }
From source file:controller.uploadProductController.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/* w ww . 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 { HttpSession session = request.getSession(true); String userPath = request.getServletPath(); if (userPath.equals("/uploadProduct")) { boolean success = true; // configures upload settings DiskFileItemFactory factory = new DiskFileItemFactory(); // sets memory threshold - beyond which files are stored in disk factory.setSizeThreshold(MEMORY_THRESHOLD); // sets temporary location to store files factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload upload = new ServletFileUpload(factory); // sets maximum size of upload file upload.setFileSizeMax(MAX_FILE_SIZE); // sets maximum size of request (include file + form data) upload.setSizeMax(MAX_REQUEST_SIZE); // constructs the directory path to store upload file // this path is relative to application's directory String uploadPath = getServletContext().getInitParameter("upload.location"); //creates a HashMap of all inputs HashMap hashMap = new HashMap(); String productId = UUID.randomUUID().toString(); try { @SuppressWarnings("unchecked") List<FileItem> formItems = upload.parseRequest(request); for (FileItem item : formItems) { // processes only fields that are not form fields if (!item.isFormField()) { File file = new File(item.getName()); File file2 = new File(productId + ".jpg"); String filePath = uploadPath + File.separator + file.getName(); // saves the file on disk File storeFile = new File(filePath); item.write(storeFile); File rename = new File(filePath); boolean flag = rename.renameTo(file2); } else { hashMap.put(item.getFieldName(), item.getString()); } } } catch (FileUploadException ex) { Logger.getLogger(uploadProductController.class.getName()).log(Level.SEVERE, null, ex); request.setAttribute("error", true); request.setAttribute("errorMessage", ex.getMessage()); success = false; } catch (Exception ex) { Logger.getLogger(uploadProductController.class.getName()).log(Level.SEVERE, null, ex); request.setAttribute("error", true); request.setAttribute("errorMessage", ex.getMessage()); success = false; } String owner = (String) session.getAttribute("customerEmail"); if (owner == null) { owner = "shop"; } String pName = hashMap.get("pName").toString(); String mNo = hashMap.get("mNo").toString(); String brand = hashMap.get("brand").toString(); String description = hashMap.get("description").toString(); String quantity = hashMap.get("quantity").toString(); String price = hashMap.get("price").toString(); String addInfo = hashMap.get("addInfo").toString(); int categoryId = Integer.parseInt(hashMap.get("category").toString()); ProductDAO productDAO = new ProductDAOImpl(); Product product; try { double priceDouble = Double.parseDouble(price); int quantityInt = Integer.parseInt(quantity); Category category = (new CategoryDAOImpl()).getCategoryFromID(categoryId); if (owner.equals("shop")) { product = new Product(productId, pName, mNo, category, quantityInt, priceDouble, brand, description, addInfo, true, true, owner); } else { product = new Product(productId, pName, mNo, category, quantityInt, priceDouble, brand, description, addInfo, false, false, owner); } if (!(productDAO.addProduct(product, category.getName()))) { throw new Exception("update unsuccessful"); } } catch (Exception e) { request.setAttribute("error", true); request.setAttribute("errorMessage", e.getMessage()); success = false; } request.setAttribute("pName", pName); request.setAttribute("mNo", mNo); request.setAttribute("brand", brand); request.setAttribute("description", description); request.setAttribute("quantity", quantity); request.setAttribute("price", price); request.setAttribute("addInfo", addInfo); request.setAttribute("categoryId", categoryId); request.setAttribute("success", success); if (success == true) { request.setAttribute("error", false); request.setAttribute("errorMessage", null); } String url; if (owner.equals("shop")) { url = "/WEB-INF/view/adminAddProducts.jsp"; } else { url = "/WEB-INF/view/clientSideView/addRecycleProduct.jsp"; } try { request.getRequestDispatcher(url).forward(request, response); } catch (ServletException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } } }
From source file:echopoint.tucana.JakartaCommonsFileUploadProvider.java
/** * @see UploadSPI#handleUpload(nextapp.echo.webcontainer.Connection , * FileUploadSelector, String, UploadProgress) *//*from w w w . java 2 s . c om*/ @SuppressWarnings({ "ThrowableInstanceNeverThrown" }) public void handleUpload(final Connection conn, final FileUploadSelector uploadSelect, final String uploadIndex, final UploadProgress progress) throws Exception { final ApplicationInstance app = conn.getUserInstance().getApplicationInstance(); final DiskFileItemFactory itemFactory = new DiskFileItemFactory(); itemFactory.setRepository(getDiskCacheLocation()); itemFactory.setSizeThreshold(getMemoryCacheThreshold()); String encoding = conn.getRequest().getCharacterEncoding(); if (encoding == null) { encoding = "UTF-8"; } final ServletFileUpload upload = new ServletFileUpload(itemFactory); upload.setHeaderEncoding(encoding); upload.setProgressListener(new UploadProgressListener(progress)); long sizeLimit = uploadSelect.getUploadSizeLimit(); if (sizeLimit == 0) sizeLimit = getFileUploadSizeLimit(); if (sizeLimit != NO_SIZE_LIMIT) { upload.setSizeMax(sizeLimit); } String fileName = null; String contentType = null; try { final FileItemIterator iter = upload.getItemIterator(conn.getRequest()); if (iter.hasNext()) { final FileItemStream stream = iter.next(); if (!stream.isFormField()) { fileName = FilenameUtils.getName(stream.getName()); contentType = stream.getContentType(); final Set<String> types = uploadSelect.getContentTypeFilter(); if (!types.isEmpty()) { if (!types.contains(contentType)) { app.enqueueTask(uploadSelect.getTaskQueue(), new InvalidContentTypeRunnable( uploadSelect, uploadIndex, fileName, contentType, progress)); return; } } progress.setStatus(Status.inprogress); final FileItem item = itemFactory.createItem(fileName, contentType, false, stream.getName()); item.getOutputStream(); // initialise DiskFileItem internals uploadSelect.notifyCallback( new UploadStartEvent(uploadSelect, uploadIndex, fileName, contentType, item.getSize())); IOUtils.copy(stream.openStream(), item.getOutputStream()); app.enqueueTask(uploadSelect.getTaskQueue(), new FinishRunnable(uploadSelect, uploadIndex, fileName, item, progress)); return; } } app.enqueueTask(uploadSelect.getTaskQueue(), new FailRunnable(uploadSelect, uploadIndex, fileName, contentType, new RuntimeException("No multi-part content!"), progress)); } catch (final FileUploadBase.SizeLimitExceededException e) { app.enqueueTask(uploadSelect.getTaskQueue(), new FailRunnable(uploadSelect, uploadIndex, fileName, contentType, new UploadSizeLimitExceededException(e), progress)); } catch (final FileUploadBase.FileSizeLimitExceededException e) { app.enqueueTask(uploadSelect.getTaskQueue(), new FailRunnable(uploadSelect, uploadIndex, fileName, contentType, new UploadSizeLimitExceededException(e), progress)); } catch (final MultipartStream.MalformedStreamException e) { app.enqueueTask(uploadSelect.getTaskQueue(), new CancelRunnable(uploadSelect, uploadIndex, fileName, contentType, e, progress)); } }
From source file:at.gv.egiz.pdfas.web.servlets.VerifyServlet.java
/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response)/* ww w.j av a 2 s .com*/ */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.info("Post verify request"); String errorUrl = PdfAsParameterExtractor.getInvokeErrorURL(request); PdfAsHelper.setErrorURL(request, response, errorUrl); StatisticEvent statisticEvent = new StatisticEvent(); statisticEvent.setStartNow(); statisticEvent.setSource(Source.WEB); statisticEvent.setOperation(Operation.VERIFY); statisticEvent.setUserAgent(UserAgentFilter.getUserAgent()); try { byte[] filecontent = null; // checks if the request actually contains upload file if (!ServletFileUpload.isMultipartContent(request)) { // No Uploaded data! if (PdfAsParameterExtractor.getPdfUrl(request) != null) { doGet(request, response); return; } else { throw new PdfAsWebException("No Signature data defined!"); } } else { // configures upload settings DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(THRESHOLD_SIZE); factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload upload = new ServletFileUpload(factory); upload.setFileSizeMax(MAX_FILE_SIZE); upload.setSizeMax(MAX_REQUEST_SIZE); // constructs the directory path to store upload file String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY; // creates the directory if it does not exist File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdir(); } List<?> formItems = upload.parseRequest(request); logger.debug(formItems.size() + " Items in form data"); if (formItems.size() < 1) { // No Uploaded data! // Try do get // No Uploaded data! if (PdfAsParameterExtractor.getPdfUrl(request) != null) { doGet(request, response); return; } else { throw new PdfAsWebException("No Signature data defined!"); } } else { for (int i = 0; i < formItems.size(); i++) { Object obj = formItems.get(i); if (obj instanceof FileItem) { FileItem item = (FileItem) obj; if (item.getFieldName().equals(UPLOAD_PDF_DATA)) { filecontent = item.get(); try { File f = new File(item.getName()); String name = f.getName(); logger.debug("Got upload: " + item.getName()); if (name != null) { if (!(name.endsWith(".pdf") || name.endsWith(".PDF"))) { name += ".pdf"; } logger.debug("Setting Filename in session: " + name); PdfAsHelper.setPDFFileName(request, name); } } catch (Throwable e) { logger.warn("In resolving filename", e); } if (filecontent.length < 10) { filecontent = null; } else { logger.debug("Found pdf Data! Size: " + filecontent.length); } } else { request.setAttribute(item.getFieldName(), item.getString()); logger.debug("Setting " + item.getFieldName() + " = " + item.getString()); } } else { logger.debug(obj.getClass().getName() + " - " + obj.toString()); } } } } if (filecontent == null) { if (PdfAsParameterExtractor.getPdfUrl(request) != null) { filecontent = RemotePDFFetcher.fetchPdfFile(PdfAsParameterExtractor.getPdfUrl(request)); } } if (filecontent == null) { Object sourceObj = request.getAttribute("source"); if (sourceObj != null) { String source = sourceObj.toString(); if (source.equals("internal")) { request.setAttribute("FILEERR", true); request.getRequestDispatcher("index.jsp").forward(request, response); statisticEvent.setStatus(Status.ERROR); statisticEvent.setException(new Exception("No file uploaded")); statisticEvent.setEndNow(); statisticEvent.setTimestampNow(); StatisticFrontend.getInstance().storeEvent(statisticEvent); statisticEvent.setLogged(true); return; } } throw new PdfAsException("No Signature data available"); } doVerify(request, response, filecontent, statisticEvent); } catch (Throwable e) { statisticEvent.setStatus(Status.ERROR); statisticEvent.setException(e); if (e instanceof PDFASError) { statisticEvent.setErrorCode(((PDFASError) e).getCode()); } statisticEvent.setEndNow(); statisticEvent.setTimestampNow(); StatisticFrontend.getInstance().storeEvent(statisticEvent); statisticEvent.setLogged(true); logger.warn("Generic Error: ", e); PdfAsHelper.setSessionException(request, response, e.getMessage(), e); PdfAsHelper.gotoError(getServletContext(), request, response); } }
From source file:com.hrhih.dispatcher.HrhihJakartaMultiPartRequest.java
private List<FileItem> parseRequest(HttpServletRequest servletRequest, String saveDir) throws FileUploadException { DiskFileItemFactory fac = createDiskFileItemFactory(saveDir); ServletFileUpload upload = new ServletFileUpload(fac); upload.setProgressListener(new FileUploadListener(servletRequest));// ? upload.setSizeMax(maxSize); return upload.parseRequest(createRequestContext(servletRequest)); }
From source file:com.example.web.Update_profile.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ String fileName = ""; int f = 0; String user = null;//from w w w. j av a 2s . co m Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals("user")) { user = cookie.getValue(); } } } String email = request.getParameter("email"); String First_name = request.getParameter("First_name"); String Last_name = request.getParameter("Last_name"); String Phone_number_1 = request.getParameter("Phone_number_1"); String Address = request.getParameter("Address"); String message = ""; int valid = 1; String query; ResultSet rs; Connection conn; String url = "jdbc:mysql://localhost:3306/"; String dbName = "tworld"; String driver = "com.mysql.jdbc.Driver"; isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { 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("/var/lib/tomcat7/webapps/www_term_project/temp/")); factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); // 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(); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); 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(); String[] spliting = fileName.split("\\."); // Write the file System.out.println(sizeInBytes + " " + maxFileSize); System.out.println(spliting[spliting.length - 1]); if (!fileName.equals("")) { if ((sizeInBytes < maxFileSize) && (spliting[spliting.length - 1].equals("jpg") || spliting[spliting.length - 1].equals("png") || spliting[spliting.length - 1].equals("jpeg"))) { 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); System.out.println("Uploaded Filename: " + fileName + "<br>"); } else { valid = 0; message = "not a valid image"; } } } BufferedReader br = null; StringBuilder sb = new StringBuilder(); String line; try { br = new BufferedReader(new InputStreamReader(fi.getInputStream())); while ((line = br.readLine()) != null) { sb.append(line); } } catch (IOException e) { } finally { if (br != null) { try { br.close(); } catch (IOException e) { } } } if (f == 0) { email = sb.toString(); } else if (f == 1) { First_name = sb.toString(); } else if (f == 2) { Last_name = sb.toString(); } else if (f == 3) { Phone_number_1 = sb.toString(); } else if (f == 4) { Address = sb.toString(); } f++; } } catch (Exception ex) { System.out.println("hi"); System.out.println(ex); } } try { Class.forName(driver).newInstance(); conn = DriverManager.getConnection(url + dbName, "admin", "admin"); if (!email.equals("")) { PreparedStatement pst = (PreparedStatement) conn .prepareStatement("update `tworld`.`users` set `email`=? where `Username`=?"); pst.setString(1, email); pst.setString(2, user); pst.executeUpdate(); pst.close(); } if (!First_name.equals("")) { PreparedStatement pst = (PreparedStatement) conn .prepareStatement("update `tworld`.`users` set `First_name`=? where `Username`=?"); pst.setString(1, First_name); pst.setString(2, user); pst.executeUpdate(); pst.close(); } if (!Last_name.equals("")) { PreparedStatement pst = (PreparedStatement) conn .prepareStatement("update `tworld`.`users` set `Last_name`=? where `Username`=?"); pst.setString(1, Last_name); pst.setString(2, user); pst.executeUpdate(); pst.close(); } if (!Phone_number_1.equals("")) { PreparedStatement pst = (PreparedStatement) conn .prepareStatement("update `tworld`.`users` set `Phone_number_1`=? where `Username`=?"); pst.setString(1, Phone_number_1); pst.setString(2, user); pst.executeUpdate(); pst.close(); } if (!Address.equals("")) { PreparedStatement pst = (PreparedStatement) conn .prepareStatement("update `tworld`.`users` set `Address`=? where `Username`=?"); pst.setString(1, Address); pst.setString(2, user); pst.executeUpdate(); pst.close(); } if (!fileName.equals("")) { PreparedStatement pst = (PreparedStatement) conn .prepareStatement("update `tworld`.`users` set `Fototitle`=? where `Username`=?"); pst.setString(1, fileName); pst.setString(2, user); pst.executeUpdate(); pst.close(); } } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException ex) { System.out.println("hi mom"); } request.setAttribute("s_page", "4"); request.getRequestDispatcher("/index.jsp").forward(request, response); } }