List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload parseRequest
public List parseRequest(HttpServletRequest request) throws FileUploadException
From source file:com.surevine.alfresco.audit.listeners.PerishableUploadDocumentAuditEventListener.java
@Override protected void populateSecondaryAuditItems(List<Auditable> events, HttpServletRequest request, HttpServletResponse response, JSONObject postContent) throws JSONException { // Create a ServletFileUpload instance to parse the form ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory()); upload.setHeaderEncoding("UTF-8"); if (ServletFileUpload.isMultipartContent(request)) { try {//w ww . j av a 2s.co m String perishableReason = null; String tags = null; for (final Object o : upload.parseRequest(request)) { FileItem item = (FileItem) o; if (item.isFormField() && "perishable".equals(item.getFieldName())) { perishableReason = item.getString(); } else if (item.isFormField() && "tags".equals(item.getFieldName())) { tags = item.getString(); } } Auditable primaryEvent = events.get(0); // If this is a site with perish reasons configured... if (_perishabilityLogic.getPerishReasons(primaryEvent.getSite()).size() > 0) { AuditItem item = new AuditItem(); setGenericAuditMetadata(item, request); // Copy any relevant fields from the primary audit event item.setNodeRef(primaryEvent.getNodeRef()); item.setVersion(primaryEvent.getVersion()); item.setSecLabel(primaryEvent.getSecLabel()); item.setSource(primaryEvent.getSource()); item.setAction(MarkPerishableAuditEventListener.ACTION); if (!StringUtils.isBlank(perishableReason)) { item.setDetails(perishableReason); } else { item.setDetails(MarkPerishableAuditEventListener.NO_PERISHABLE_MARK); } if (tags != null) { item.setTags(StringUtils.join(tags.trim().split(" "), ',')); } events.add(item); } } catch (FileUploadException e) { logger.error("Error while parsing request form", e); } } }
From source file:com.esteban.cmms.maven.controller.Imagenes_Controller.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.// www . j a v a 2 s. 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 { String btne = request.getParameter("btn"); if (btne == null) { try { HttpSession sesion = request.getSession(); sesion.removeAttribute("imagenes"); Usuarios user = (Usuarios) sesion.getAttribute("usuario"); FileItemFactory itemFactory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(itemFactory); String btn = null; Maquinas m = new Maquinas(); List<FileItem> items = upload.parseRequest(request); Imagenes pojo = new Imagenes(); pojo.setUserAction(user.getNombre()); for (FileItem item : items) { if (!item.isFormField()) { String contentType = item.getContentType(); if (!contentType.equals("image/png")) { //|| !contentType.equals("image/jpg") continue; } File img = new File( "/home/esteban/NetBeansProjects/" + "CMMS-Maven/src/main/webapp/Imagenes/images_cli", new Date() + item.getName()); item.write(img); pojo.setImagen(img.getName()); } if (item.isFormField()) { if (item.getFieldName().equalsIgnoreCase("maquina")) { int idm = Integer.parseInt(item.getString()); System.out.println("Maquina"); m.setId(idm); pojo.setMaquinas(m); } else if (item.getFieldName().equalsIgnoreCase("btn")) { System.out.println("Guardar cambios"); btn = item.getString().replaceAll("\\s", ""); } else if (item.getFieldName().equalsIgnoreCase("id")) { System.out.println("id imagen"); pojo.setId(Integer.parseInt(item.getString())); } } } pojo.setEstado("Activo"); System.out.println("ste es el boton" + btn); if (btn.equalsIgnoreCase("actualizar")) { new Imagenes_Model().updateImagen(pojo); } else { new Imagenes_Model().addImagen(pojo); } response.sendRedirect("Imagenes"); } catch (FileUploadException ex) { System.out.println(ex); response.sendRedirect("Static_pages/errores.jsp"); } catch (Exception ex) { System.out.println(ex); response.sendRedirect("Static_pages/errores.jsp"); } } else { String btn = btne.replaceAll("\\s", ""); if (btn.equalsIgnoreCase("imagenes")) { Imagenes_Model model = new Imagenes_Model(); HttpSession sesion = request.getSession(); String valor = request.getParameter("valor"); List<Imagenes> result = new ArrayList<Imagenes>(); if (valor.equalsIgnoreCase("activo")) { try { result = model.getAllImagenes(); sesion.setAttribute("imagenes", result); sesion.setAttribute("maquinas", new Maquinas_Model().getAllMaquinas()); } catch (Exception e) { System.out.println(e); response.sendRedirect("Static_pages/errores.jsp"); } response.sendRedirect("Imagenes"); } else if (valor.equalsIgnoreCase("inactivo")) { try { result = model.listNoActive(); sesion.setAttribute("imagenes", result); } catch (Exception e) { System.out.println(e); response.sendRedirect("Static_pages/errores.jsp"); } response.sendRedirect("Imagenes/archivados.jsp"); } } else if (btn.equalsIgnoreCase("estado")) { System.out.println("Definicin de estado"); System.out.println("Nuevo estado: " + request.getParameter("estado")); Usuarios user = (Usuarios) request.getSession().getAttribute("usuario"); try { new Imagenes_Model().estadoImagen(request.getParameter("estado"), Integer.parseInt(request.getParameter("id")), user.getNombre()); } catch (Exception ex) { System.out.println(ex); response.sendRedirect("Static_pages/errores.jsp"); } System.out.println("Estado definido con xito"); response.sendRedirect("Imagenes"); } } }
From source file:com.eufar.asmm.server.UploadImage.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("UploadImage - the function started"); DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(MAX_MEMORY_SIZE); String uploadFolder = getServletContext().getRealPath("") + DATA_DIRECTORY; ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(MAX_REQUEST_SIZE); double maxSize = (MAX_REQUEST_SIZE / 1024) / 1024; System.out.println("UploadImage - max image size: " + maxSize + " Mbytes"); try {/*w w w.ja v a 2s . c o m*/ @SuppressWarnings("rawtypes") List items = upload.parseRequest(request); @SuppressWarnings("rawtypes") Iterator iter = items.iterator(); while (iter.hasNext()) { Object obj = iter.next(); org.apache.commons.fileupload.FileItem item = (org.apache.commons.fileupload.FileItem) obj; String fileExt = FilenameUtils.getExtension(item.getName()); if (fileExt.matches("(jpg|jpeg|bmp|png|JPG|JPEG|BMP|PNG)")) { System.out.println("UploadImage - image accepted"); if (!item.isFormField()) { File uploadedFile = File.createTempFile("tmp_", "." + fileExt, new File(uploadFolder)); item.write(uploadedFile); double fileSize = item.getSize(); fileSize = (fileSize / 1024) / 1024; response.setCharacterEncoding("UTF-8"); response.setContentType("text/html"); response.getWriter().write(uploadedFile.getName()); System.out.println("UploadImage - " + uploadedFile.getPath() + ": upload ok..."); System.out.println("UploadImage - " + uploadedFile.getPath() + ": " + fileSize + " MBytes"); if (new File(uploadedFile.getPath()).isFile()) { System.out.println("PrintFunction - picture (webapps): the file exists."); } else { System.out.println("PrintFunction - picture (webapps): the file doesn't exist."); } if (new File(uploadedFile.getPath()).isFile()) { System.out.println("PrintFunction - picture (webapps): the file can be read."); } else { System.out.println("PrintFunction - picture (webapps): the file can't be read."); } } else { System.out.println("UploadImage - a problem occured with the file format"); } } else { System.out.println("UploadImage - image rejected: wrong format"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html"); response.getWriter().write("format"); } } } catch (Exception ex) { System.out.println("UploadImage - a problem occured: " + ex); response.getWriter().write("ERROR:" + ex.getMessage()); } }
From source file:com.orinus.script.safe.jetty.SRequest.java
public void parseMultipartContent() { if (formFields != null && formFiles != null && formFileData != null) return;/* www .jav a 2s .c om*/ formFields = new HashMap<String, String>(); formFiles = new HashMap<String, FileEntry>(); formFileData = new HashMap<String, String>(); try { DiskFileItemFactory factory = new DiskFileItemFactory(); Controller controller = new Controller(); factory.setRepository(new File(controller.getTempDir())); ServletFileUpload upload = new ServletFileUpload(factory); List items = upload.parseRequest(req); for (int i = 0; i < items.size(); i++) { FileItem item = (FileItem) items.get(i); if (item.isFormField()) { formFields.put(item.getFieldName(), item.getString()); } else { FileEntry fe = new FileEntry(); fe.fieldName = item.getFieldName(); fe.contentType = item.getContentType(); fe.filename = new File(item.getName()).getName(); fe.fileSize = item.getSize(); String filename = new File(controller.getTempDir(), fe.filename).getAbsolutePath(); item.write(new File(filename)); formFiles.put(fe.fieldName, fe); formFileData.put(fe.fieldName, filename); } } } catch (Exception e) { } }
From source file:com.servlet.UpdateClaim.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request//from w w w .j a v a2s . 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 { PrintWriter out = response.getWriter(); double total = 0; //variable declaration FileItem item = null; String fieldName = ""; String fieldValue = ""; String fileName = ""; boolean isImageExist = false; //current sessions Employee emp = (Employee) request.getSession().getAttribute("user"); Claims cla = (Claims) request.getSession().getAttribute("c"); //bean object Claims claims = new Claims(); boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { List items = upload.parseRequest(request); Iterator iterator = items.iterator(); while (iterator.hasNext()) { item = (FileItem) iterator.next(); if (!item.isFormField()) { // check for regular form field fileName = item.getName(); if (!fileName.equals("")) { String root = getServletContext().getRealPath("/"); response.getWriter().write(root); File path = new File(root + "/images/uploads" + File.separator + "Claims" + File.separator + cla.getClaimId()); String filePath = "images/uploads/Claims/" + cla.getClaimId() + "/" + fileName; filePath = filePath.replace("\\", "/"); if (!path.exists()) { boolean status = path.mkdirs(); } //File uploadedFile = new File(path + "/" + fileName); // for copy file File uploadedFile = new File(path + "/" + fileName); // for copy file item.write(uploadedFile); isImageExist = true; claims.setAttachment(filePath);//save the url in databse } else { isImageExist = false; } } else { fieldName = item.getFieldName();// field name of current File item fieldValue = item.getString(); if (fieldName.equals("docid")) { claims.setDocId(Integer.parseInt(fieldValue)); } else if (fieldName.equals("claim_group")) { claims.setClaimGroup(fieldValue); } else if (fieldName.equals("type_of_claim")) {//bill type claims.setBillType(fieldValue); } else if (fieldName.equals("food_type")) {//meal type claims.setMealType(fieldValue); } else if (fieldName.equals("bill_date")) { claims.setBillDate(fieldValue); } else if (fieldName.equals("amount")) { claims.setAmount(Double.parseDouble(fieldValue)); } else if (fieldName.equals("project")) { claims.setProject(fieldValue); } else if (fieldName.equals("description")) { claims.setDescription(fieldValue); } else if (fieldName.equals("employeesId")) { claims.setEmpListId(fieldValue); } //////////////////// } } //end of while DBcon dbcon = new DBcon(); dbcon.getDbCon();// set up the database connection DBCollection coll = dbcon.getData("claims"); BasicDBObject search = new BasicDBObject("claimid", cla.getClaimId()); search.append("details.docid", claims.getDocId()); DBObject obj = claims.toDBObject();//create DBObject from data BasicDBObject update = new BasicDBObject(); update.append("details.$.claimgroup", claims.getClaimGroup()); update.append("details.$.billtype", claims.getBillType()); update.append("details.$.mealtype", claims.getMealType()); update.append("details.$.bill_date", claims.getBillDate()); update.append("details.$.amount", claims.getAmount()); update.append("details.$.project", claims.getProject()); update.append("details.$.description", claims.getDescription()); update.append("details.$. employeesId", claims.getEmpListId()); if (isImageExist) { update.append("details.$.attachment", claims.getAttachment()); } BasicDBObject push = new BasicDBObject("$set", update); dbcon.updateData("claims", search, push);//update the new document DBCursor cursor = coll.find(search); DBObject findMainObject = cursor.next(); Claims mainClaimObject = Claims.fromDBObject2(findMainObject);//create a main claim object ArrayList list = mainClaimObject.getDetails(); Iterator<BasicDBObject> intI = list.iterator(); while (intI.hasNext()) { BasicDBObject o = intI.next(); Claims cl = Claims.fromDBObject(o); total += cl.getAmount(); } mainClaimObject.setTotal(total);//update the total claim amount*/ DBObject mainObject = mainClaimObject.toDBObject2(); dbcon.updateData("claims", search, mainObject);//update the new document response.sendRedirect("home_page_claim_add.jsp"); } catch (FileUploadException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } }
From source file:com.manning.cmis.theblend.servlets.AddServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response, Session session) throws ServletException, IOException, TheBlendException { // check for multipart content boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) { // we expected content -> return to add page dispatch("add.jsp", "Add something new. The Blend.", request, response); }/*w ww. j av a 2s . c o m*/ Map<String, Object> properties = new HashMap<String, Object>(); File uploadedFile = null; String parentId = null; String parentPath = null; ObjectId newId = null; // process the request try { DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(50 * 1024 * 1024); @SuppressWarnings("unchecked") List<FileItem> items = upload.parseRequest(request); Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (item.isFormField()) { String name = item.getFieldName(); if (PARAM_PARENT_ID.equalsIgnoreCase(name)) { parentId = item.getString(); } else if (PARAM_PARENT_PATH.equalsIgnoreCase(name)) { parentPath = item.getString(); } else if (PARAM_TYPE_ID.equalsIgnoreCase(name)) { properties.put(PropertyIds.OBJECT_TYPE_ID, item.getString()); } } else { String name = item.getName(); if (name == null) { name = "file"; } else { // if the browser provided a path instead of a file name, // strip off the path int x = name.lastIndexOf('/'); if (x > -1) { name = name.substring(x + 1); } x = name.lastIndexOf('\\'); if (x > -1) { name = name.substring(x + 1); } name = name.trim(); if (name.length() == 0) { name = "file"; } } properties.put(PropertyIds.NAME, name); uploadedFile = File.createTempFile("blend", "tmp"); item.write(uploadedFile); } } } catch (Exception e) { throw new TheBlendException("Upload failed: " + e, e); } if (uploadedFile == null) { throw new TheBlendException("No content!"); } try { // prepare the content stream ContentStream contentStream = null; try { String objectTypeId = (String) properties.get(PropertyIds.OBJECT_TYPE_ID); contentStream = prepareContentStream(session, uploadedFile, objectTypeId, properties); } catch (Exception e) { throw new TheBlendException("Upload failed: " + e, e); } // find the parent folder // (we don't deal with unfiled documents here) Folder parent = null; if (parentId != null) { parent = CMISHelper.getFolder(session, parentId, CMISHelper.LIGHT_OPERATION_CONTEXT, "parent folder"); } else { parent = CMISHelper.getFolderByPath(session, parentPath, CMISHelper.LIGHT_OPERATION_CONTEXT, "parent folder"); } // create the document try { newId = session.createDocument(properties, parent, contentStream, null); } catch (CmisBaseException cbe) { throw new TheBlendException("Could not create document: " + cbe.getMessage(), cbe); } finally { try { contentStream.getStream().close(); } catch (IOException ioe) { // ignore } } } finally { // delete temp file uploadedFile.delete(); } // show the newly created document redirect(HTMLHelper.encodeUrlWithId(request, "show", newId.getId()), request, response); }
From source file:com.openkm.extension.servlet.ZohoFileUploadServlet.java
@SuppressWarnings("unchecked") protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.info("service({}, {})", request, response); boolean isMultipart = ServletFileUpload.isMultipartContent(request); InputStream is = null;// ww w . j ava 2 s . co m String id = ""; if (isMultipart) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("UTF-8"); // Parse the request and get all parameters and the uploaded file List<FileItem> items; try { items = upload.parseRequest(request); for (Iterator<FileItem> it = items.iterator(); it.hasNext();) { FileItem item = it.next(); if (item.isFormField()) { // if (item.getFieldName().equals("format")) { format = // item.getString("UTF-8"); } if (item.getFieldName().equals("id")) { id = item.getString("UTF-8"); } // if (item.getFieldName().equals("filename")) { // filename = item.getString("UTF-8"); } } else { is = item.getInputStream(); } } // Retrieve token ZohoToken zot = ZohoTokenDAO.findByPk(id); // Save document if (Config.REPOSITORY_NATIVE) { String sysToken = DbSessionManager.getInstance().getSystemToken(); String path = OKMRepository.getInstance().getNodePath(sysToken, zot.getNode()); new DbDocumentModule().checkout(sysToken, path, zot.getUser()); new DbDocumentModule().checkin(sysToken, path, is, "Modified from Zoho", zot.getUser()); } else { String sysToken = JcrSessionManager.getInstance().getSystemToken(); String path = OKMRepository.getInstance().getNodePath(sysToken, zot.getNode()); new JcrDocumentModule().checkout(sysToken, path, zot.getUser()); new JcrDocumentModule().checkin(sysToken, path, is, "Modified from Zoho", zot.getUser()); } } catch (FileUploadException e) { log.error(e.getMessage(), e); } catch (PathNotFoundException e) { log.error(e.getMessage(), e); } catch (RepositoryException e) { log.error(e.getMessage(), e); } catch (DatabaseException e) { log.error(e.getMessage(), e); } catch (FileSizeExceededException e) { log.error(e.getMessage(), e); } catch (UserQuotaExceededException e) { log.error(e.getMessage(), e); } catch (VirusDetectedException e) { log.error(e.getMessage(), e); } catch (VersionException e) { log.error(e.getMessage(), e); } catch (LockException e) { log.error(e.getMessage(), e); } catch (AccessDeniedException e) { log.error(e.getMessage(), e); } catch (ExtensionException e) { log.error(e.getMessage(), e); } catch (AutomationException e) { log.error(e.getMessage(), e); } finally { IOUtils.closeQuietly(is); } } }
From source file:com.windy.zfxy.fck.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. * // www. jav a2 s. com * @param request * the current request instance * @return the upload response instance associated with this request */ @SuppressWarnings("unchecked") UploadResponse doPost(final HttpServletRequest request) { logger.debug("Entering Dispatcher#doPost"); Context context = ThreadLocalData.getContext(); context.logBaseParameters(); UploadResponse uploadResponse = null; // check permissions for user actions if (!RequestCycleHandler.isFileUploadEnabled(request)) uploadResponse = UploadResponse.getFileUploadDisabledError(); // check parameters 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 ResourceType type = context.getDefaultResourceType(); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { List<FileItem> items = upload.parseRequest(request); // We upload just one file at the same time FileItem uplFile = items.get(0); // Some browsers transfer the entire source path not just the // filename String fileName = FilenameUtils.getName(uplFile.getName()); fileName = java.util.UUID.randomUUID().toString() + "." + FilenameUtils.getExtension(fileName); logger.debug("Parameter NewFile: {}", fileName); // check the extension if (type.isDeniedExtension(FilenameUtils.getExtension(fileName))) uploadResponse = UploadResponse.getInvalidFileTypeError(); // Secure image check (can't be done if QuickUpload) else if (type.equals(ResourceType.IMAGE) && PropertiesLoader.isSecureImageUploads() && !UtilsFile.isImage(uplFile.getInputStream())) { uploadResponse = UploadResponse.getInvalidFileTypeError(); } else { String sanitizedFileName = UtilsFile.sanitizeFileName(fileName); logger.debug("Parameter NewFile (sanitized): {}", sanitizedFileName); String newFileName = connector.fileUpload(type, context.getCurrentFolderStr(), sanitizedFileName, uplFile.getInputStream()); String fileUrl = UtilsResponse.fileUrl(RequestCycleHandler.getUserFilesPath(request), type, context.getCurrentFolderStr(), newFileName); // this.setPhotoPath(fileUrl); if (sanitizedFileName.equals(newFileName)) { uploadResponse = UploadResponse.getOK(fileUrl); } else { uploadResponse = UploadResponse.getFileRenamedWarning(fileUrl, newFileName); logger.debug("Parameter NewFile (renamed): {}", newFileName); } } uplFile.delete(); } catch (InvalidCurrentFolderException e) { uploadResponse = UploadResponse.getInvalidCurrentFolderError(); } catch (WriteException e) { uploadResponse = UploadResponse.getFileUploadWriteError(); } catch (IOException e) { uploadResponse = UploadResponse.getFileUploadWriteError(); } catch (FileUploadException e) { uploadResponse = UploadResponse.getFileUploadWriteError(); } } logger.debug("Exiting Dispatcher#doPost"); return uploadResponse; }
From source file:com.sun.socialsite.web.rest.servlets.UploadServlet.java
/** * Note: using SuppressWarnings annotation because the Commons FileUpload API is * not genericized./* w w w .j a v a2 s . c o m*/ */ @Override @SuppressWarnings(value = "unchecked") protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { // ensure calling app/gadget has perm to use SocialSite API SecurityToken token = new AuthInfo(req).getSecurityToken(); Factory.getSocialSite().getPermissionManager().checkPermission(requiredPerm, token); GroupManager gmgr = Factory.getSocialSite().getGroupManager(); ProfileManager pmgr = Factory.getSocialSite().getProfileManager(); int errorCode = -1; Group group = null; Profile profile = null; // parse URL to get route and subjectId String route = null; String subjectId = ""; if (req.getPathInfo() != null) { String[] pathInfo = req.getPathInfo().split("/"); route = pathInfo[1]; subjectId = pathInfo[2]; } // first, figure out destination profile or group and check the // caller's permission to upload an image for that profile or group if ("profile".equals(route)) { if (token.getViewerId().equals(subjectId)) { profile = pmgr.getProfileByUserId(subjectId); } else { errorCode = HttpServletResponse.SC_UNAUTHORIZED; } } else if ("group".equals(route)) { group = gmgr.getGroupByHandle(subjectId); if (group != null) { // ensure called is group ADMIN or founder Profile viewer = pmgr.getProfileByUserId(token.getViewerId()); GroupRelationship grel = gmgr.getMembership(group, viewer); if (grel == null || (grel.getRelcode() != GroupRelationship.Relationship.ADMIN && grel.getRelcode() != GroupRelationship.Relationship.FOUNDER)) { } else { errorCode = HttpServletResponse.SC_UNAUTHORIZED; } } else { // group not found errorCode = HttpServletResponse.SC_NOT_FOUND; } } // next, parse out the image and save it in profile or group if (errorCode != -1 && group == null && profile == null) { errorCode = HttpServletResponse.SC_NOT_FOUND; } else if (errorCode == -1) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); FileItem fileItem = null; List<FileItem> items = (List<FileItem>) upload.parseRequest(req); if (items.size() > 0) { fileItem = items.get(0); } if ((fileItem != null) && (types.contains(fileItem.getContentType()))) { // read incomining image via Commons Upload InputStream is = fileItem.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); Utilities.copyInputToOutput(is, baos); byte[] byteArray = baos.toByteArray(); // save it in the profile or group indicated if (profile != null) { profile.setImageType(fileItem.getContentType()); profile.setImage(byteArray); pmgr.saveProfile(profile); Factory.getSocialSite().flush(); } else if (group != null) { group.setImageType(fileItem.getContentType()); group.setImage(byteArray); gmgr.saveGroup(group); Factory.getSocialSite().flush(); } else { // group or profile not indicated properly errorCode = HttpServletResponse.SC_NOT_FOUND; } } } if (errorCode == -1) { resp.sendError(HttpServletResponse.SC_OK); return; } else { resp.sendError(errorCode); } } catch (SecurityException sx) { log.error("Permission denied", sx); resp.sendError(HttpServletResponse.SC_UNAUTHORIZED); } catch (FileUploadException fx) { log.error("ERROR uploading profile image", fx); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } catch (SocialSiteException ex) { log.error("ERROR saving profile image", ex); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } }
From source file:com.wakasta.tubes2.AddProductPost.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String item_data = ""; // 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;//from w w w. j av a 2 s . co m } 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>"); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { // Get the uploaded file parameters String fieldName = fi.getFieldName(); String 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)); } item_data = Base64.encodeBase64String(fi.get()); fi.write(file); // out.println("Uploaded Filename: " + fileName + "<br>"); // out.println(file); } } out.println("</body>"); out.println("</html>"); } catch (FileUploadException ex) { Logger.getLogger(AddProductPost.class.getName()).log(Level.SEVERE, null, ex); } catch (java.lang.Exception ex) { Logger.getLogger(AddProductPost.class.getName()).log(Level.SEVERE, null, ex); } }