List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload isMultipartContent
public static final boolean isMultipartContent(HttpServletRequest request)
From source file:Algorithm.RequestParser.java
public static InputStream getStream(HttpServletRequest request) throws FileUploadException, IOException { if (ServletFileUpload.isMultipartContent(request)) { List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); for (FileItem item : multiparts) { if (!item.isFormField()) { InputStream img = item.getInputStream(); return img; }//from w w w .ja va2s .c o m } } return null; }
From source file:de.micromata.genome.gwiki.page.impl.actionbean.CommonMutipartRequestHandler.java
@SuppressWarnings({ "unchecked" }) public static void handleMultiPartRequest(GWikiContext ctx) { if (ServletFileUpload.isMultipartContent(ctx.getRequest()) == false) { return;// w w w. j a v a 2 s.c om } try { ServletFileUpload sfc = new ServletFileUpload(ctx.getWikiWeb().getDaoContext().getFileItemFactory()); List<FileItem> files = (List<FileItem>) sfc.parseRequest(ctx.getRequest()); CommonMultipartRequest req = new CommonMultipartRequest(ctx.getRequest()); for (FileItem fi : files) { if (fi.isFormField() == true) { req.addFormField(fi); } else { req.addFileItem(fi); } } ctx.setRequest(req); } catch (Exception ex) { GWikiLog.warn("Failed to upload file: " + ex.getMessage(), ex); ctx.addSimpleValidationError("Failed to upload: " + ex.getMessage()); } }
From source file:io.kloudwork.util.MultipartFormHandler.java
public static MultipartParamHolder handle(Request request) throws IOException, FileUploadException { if (!ServletFileUpload.isMultipartContent(request.raw())) { return parseContent(request); }/*w ww . j av a 2s. co m*/ ServletFileUpload servletFileUpload = new ServletFileUpload(); FileItemIterator iterator = servletFileUpload.getItemIterator(request.raw()); Map<String, String> postParameters = new HashMap<>(); Map<String, FileItemStream> files = new HashMap<>(); while (iterator.hasNext()) { FileItemStream fileItem = iterator.next(); if (fileItem.isFormField()) { try (InputStream is = fileItem.openStream()) { postParameters.put(fileItem.getFieldName(), Streams.asString(is)); } } else { files.put(fileItem.getFieldName(), fileItem); } } if (files.isEmpty()) { return new MultipartParamHolder(postParameters); } return new MultipartParamHolder(postParameters, files); }
From source file:beans.service.FileUploadTool.java
static public String FileUpload(Map<String, String> fields, List<String> filesOnServer, HttpServletRequest request, HttpServletResponse response) { boolean isMultipart = ServletFileUpload.isMultipartContent(request); DiskFileItemFactory factory = new DiskFileItemFactory(); int MaxMemorySize = 10000000; int MaxRequestSize = MaxMemorySize; String tmpDir = System.getProperty("TMP", "/tmp"); System.out.printf("temporary directory:%s", tmpDir); factory.setSizeThreshold(MaxMemorySize); factory.setRepository(new File(tmpDir)); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Set overall request size constraint upload.setSizeMax(MaxRequestSize);//from ww w . j a v a2 s . c o m // Parse the request try { List<FileItem> items = upload.parseRequest(request); // Process the uploaded items Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (item.isFormField()) {//k -v String name = item.getFieldName(); String value = item.getString(); fields.put(name, value); } else { String fieldName = item.getFieldName(); String fileName = item.getName(); if (fileName == null || fileName.length() < 1) { return "file name is empty."; } String localFileName = ServletConfig.fileServerRootDir + File.separator + "tmp" + File.separator + fileName; System.out.printf("upload file:%s", localFileName); String contentType = item.getContentType(); boolean isInMemory = item.isInMemory(); long sizeInBytes = item.getSize(); File uploadedFile = new File(localFileName); item.write(uploadedFile); filesOnServer.add(localFileName); } } return "success"; } catch (FileUploadException e) { e.printStackTrace(); return e.toString(); } catch (Exception e) { e.printStackTrace(); return e.toString(); } }
From source file:in.xebia.poc.FileUploadUtils.java
public static boolean parseFileUploadRequest(HttpServletRequest request, File outputFile, Map<String, String> params) throws Exception { log.debug("Request class? " + request.getClass().toString()); log.debug("Request is multipart? " + ServletFileUpload.isMultipartContent(request)); log.debug("Request method: " + request.getMethod()); log.debug("Request params: "); for (Object key : request.getParameterMap().keySet()) { log.debug((String) key);/*from www. ja v a2 s.com*/ } log.debug("Request attribute names: "); boolean filedataInAttributes = false; Enumeration attrNames = request.getAttributeNames(); while (attrNames.hasMoreElements()) { String attrName = (String) attrNames.nextElement(); log.debug(attrName); if ("filedata".equals(attrName)) { filedataInAttributes = true; } } if (filedataInAttributes) { log.debug("Found filedata in request attributes, getting it out..."); log.debug("filedata class? " + request.getAttribute("filedata").getClass().toString()); FileItem item = (FileItem) request.getAttribute("filedata"); item.write(outputFile); for (Object key : request.getParameterMap().keySet()) { params.put((String) key, request.getParameter((String) key)); } return true; } /*ServletFileUpload upload = new ServletFileUpload(); //upload.setSizeMax(Globals.MAX_UPLOAD_SIZE); FileItemIterator iter = upload.getItemIterator(request); while(iter.hasNext()){ FileItemStream item = iter.next(); InputStream stream = item.openStream(); //If this item is a file if(!item.isFormField()){ log.debug("Found non form field in upload request with field name = " + item.getFieldName()); String name = item.getName(); if(name == null){ throw new Exception("File upload did not have filename specified"); } // Some browsers, including IE, return the full path so trim off everything but the file name name = getFileNameFromPath(name); //Enforce required file extension, if present if(!name.toLowerCase().endsWith( ".zip" )){ throw new Exception("File uploaded did not have required extension .zip"); } bufferedCopyStream(stream, new FileOutputStream(outputFile)); } else { params.put(item.getFieldName(), Streams.asString(stream)); } } return true;*/ // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request List /* FileItem */ items = upload.parseRequest(request); // Process the uploaded items Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { log.debug("Found non form field in upload request with field name = " + item.getFieldName()); String name = item.getName(); if (name == null) { throw new Exception("File upload did not have filename specified"); } // Some browsers, including IE, return the full path so trim off everything but the file name name = getFileNameFromPath(name); item.write(outputFile); } else { params.put(item.getFieldName(), item.getString()); } } return true; }
From source file:database.FileMgr.java
public void upload(HttpServletRequest request) throws Exception { boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List items = upload.parseRequest(request); Iterator iterator = items.iterator(); while (iterator.hasNext()) { FileItem item = (FileItem) iterator.next(); if (!item.isFormField()) { String fileName = item.getName(); if (!path.exists()) { boolean status = path.mkdirs(); }//from ww w . j av a 2s .co m String dir = path + "/" + fileName; File uploadedFile = new File(dir); if (!(uploadedFile.exists() && !uploadedFile.isDirectory())) { //System.out.println(uploadedFile.getAbsolutePath()); item.write(uploadedFile); } else { throw new Exception("File exist"); } } } } }
From source file:msec.org.FileUploadServlet.java
static protected String FileUpload(Map<String, String> fields, List<String> filesOnServer, HttpServletRequest request, HttpServletResponse response) { boolean isMultipart = ServletFileUpload.isMultipartContent(request); // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); int MaxMemorySize = 10000000; int MaxRequestSize = MaxMemorySize; String tmpDir = System.getProperty("TMP", "/tmp"); //System.out.printf("temporary directory:%s", tmpDir); // Set factory constraints factory.setSizeThreshold(MaxMemorySize); factory.setRepository(new File(tmpDir)); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("utf8"); // Set overall request size constraint upload.setSizeMax(MaxRequestSize);// ww w . j a va 2s .com // Parse the request try { @SuppressWarnings("unchecked") List<FileItem> items = upload.parseRequest(request); // Process the uploaded items Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (item.isFormField()) {//k -v String name = item.getFieldName(); String value = item.getString("utf-8"); fields.put(name, value); } else { String fieldName = item.getFieldName(); String fileName = item.getName(); if (fileName == null || fileName.length() < 1) { return "file name is empty."; } String localFileName = ServletConfig.fileServerRootDir + File.separator + "tmp" + File.separator + fileName; //System.out.printf("upload file:%s", localFileName); String contentType = item.getContentType(); boolean isInMemory = item.isInMemory(); long sizeInBytes = item.getSize(); File uploadedFile = new File(localFileName); item.write(uploadedFile); filesOnServer.add(localFileName); } } return "success"; } catch (FileUploadException e) { e.printStackTrace(); return e.toString(); } catch (Exception e) { e.printStackTrace(); return e.toString(); } }
From source file:com.bdnc.ecommercebdnc.command.CadastraProduto.java
@Override public void execute(HttpServletRequest request, HttpServletResponse response) { boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = null; try {/* www. ja va2 s .c om*/ items = (List<FileItem>) upload.parseRequest(request); Produto produto = new Produto(); produto.setFoto(items.get(0).get()); produto.setDescricao(items.get(1).getString("UTF-8")); produto.setValor(Double.parseDouble(items.get(2).getString("UTF-8"))); LojaService lojaService = new LojaService(); lojaService.salvarProduto(produto); request.getSession().setAttribute("produtos", lojaService.listarProdutos()); RequestDispatcher dispather = request.getRequestDispatcher("cadastroproduto.jsp"); dispather.forward(request, response); } catch (Exception ex) { ex.printStackTrace(); } } }
From source file:com.elit2.app.control.FileUpload.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("text/html"); boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { ServletFileUpload upload = new ServletFileUpload(); try {// www . jav a 2 s . c om FileItemIterator itr = upload.getItemIterator(request); while (itr.hasNext()) { FileItemStream item = itr.next(); if (item.isFormField()) { String fieldName = item.getFieldName(); InputStream is = item.openStream(); byte[] b = new byte[is.available()]; is.read(b); String value = new String(b); response.getWriter().println(fieldName + ":" + value + "<br/>"); } else { String path = getServletContext().getRealPath("/"); if (com.elit2.app.model.FileUpload.proccessFile(path, item)) { response.getWriter().print("Deu certo"); } else { response.getWriter().print("Deu errado"); } } } } catch (FileUploadException ex) { ex.printStackTrace(); } } }
From source file:dataMappers.PictureDataMapper.java
public static void addPictureToReport(DBConnector dbconnector, HttpServletRequest request) throws FileUploadException, IOException, SQLException { if (!ServletFileUpload.isMultipartContent(request)) { System.out.println("Invalid upload request"); return;// w w w . j av a 2 s . c om } // Define limits for disk item DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(THRESHOLD_SIZE); // Define limit for servlet upload ServletFileUpload upload = new ServletFileUpload(factory); upload.setFileSizeMax(MAX_FILE_SIZE); upload.setSizeMax(MAX_REQUEST_SIZE); FileItem itemFile = null; int reportID = 0; // Get list of items in request (parameters, files etc.) List formItems = upload.parseRequest(request); Iterator iter = formItems.iterator(); // Loop items while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { itemFile = item; // If not form field, must be item } else if (item.getFieldName().equalsIgnoreCase("reportID")) { // else it is a form field try { System.out.println(item.getString()); reportID = Integer.parseInt(item.getString()); } catch (NumberFormatException e) { reportID = 0; } } } // This will be null if no fields were declared as image/upload. // Also, reportID must be > 0 if (itemFile != null || reportID == 0) { try { // Create credentials from final vars BasicAWSCredentials awsCredentials = new BasicAWSCredentials(AMAZON_ACCESS_KEY, AMAZON_SECRET_KEY); // Create client with credentials AmazonS3 s3client = new AmazonS3Client(awsCredentials); // Set region s3client.setRegion(Region.getRegion(Regions.EU_WEST_1)); // Set content length (size) of file ObjectMetadata om = new ObjectMetadata(); om.setContentLength(itemFile.getSize()); // Get extension for file String ext = FilenameUtils.getExtension(itemFile.getName()); // Generate random filename String keyName = UUID.randomUUID().toString() + '.' + ext; // This is the actual upload command s3client.putObject(new PutObjectRequest(S3_BUCKET_NAME, keyName, itemFile.getInputStream(), om)); // Picture was uploaded to S3 if we made it this far. Now we insert the row into the database for the report. PreparedStatement stmt = dbconnector.getCon() .prepareStatement("INSERT INTO reports_pictures" + "(REPORTID, PICTURE) VALUES (?,?)"); stmt.setInt(1, reportID); stmt.setString(2, keyName); stmt.executeUpdate(); stmt.close(); } 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()); } catch (AmazonClientException ace) { System.out.println("Caught an AmazonClientException, which " + "means the client encountered " + "an internal error while trying to " + "communicate with S3, " + "such as not being able to access the network."); System.out.println("Error Message: " + ace.getMessage()); } } }