Example usage for org.apache.commons.fileupload.servlet ServletFileUpload parseRequest

List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload parseRequest

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.servlet ServletFileUpload parseRequest.

Prototype

public List  parseRequest(HttpServletRequest request) throws FileUploadException 

Source Link

Document

Processes an <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC 1867</a> compliant <code>multipart/form-data</code> stream.

Usage

From source file:it.biblio.servlets.Modificapub.java

/**
 * metodo per gestire l'upload di file e inserimento dati
 *
 * @param request// ww w .  j av  a 2s  .c  om
 * @param response
 * @return
 * @throws IOException
 */
private boolean upload(HttpServletRequest request) throws IOException, SQLException, Exception {
    HttpSession s = SecurityLayer.checkSession(request);

    Map<String, Object> pub = new HashMap<String, Object>();
    Map<String, Object> ristampe = new HashMap<String, Object>();
    Map<String, Object> keyword = new HashMap<String, Object>();
    Map<String, Object> storyboard = new HashMap<String, Object>();

    if (ServletFileUpload.isMultipartContent(request)) {
        FileItemFactory fif = new DiskFileItemFactory();
        ServletFileUpload sfo = new ServletFileUpload(fif);
        List<FileItem> items = sfo.parseRequest(request);
        for (FileItem item : items) {
            String fname = item.getFieldName();
            if (item.isFormField() && fname.equals("titolo") && !item.getString().isEmpty()) {
                pub.put("titolo", item.getString());
            } else if (item.isFormField() && fname.equals("autore") && !item.getString().isEmpty()) {
                pub.put("Autore", item.getString());
            } else if (item.isFormField() && fname.equals("descrizione") && !item.getString().isEmpty()) {
                pub.put("descrizione", item.getString());
            } else if (item.isFormField() && fname.equals("categoria") && !item.getString().isEmpty()) {
                pub.put("categoria", item.getString());
            } else if (item.isFormField() && fname.equals("ISBN") && !item.getString().isEmpty()) {
                ristampe.put("isbn", item.getString());
            } else if (item.isFormField() && fname.equals("numero_pagine") && !item.getString().isEmpty()) {
                ristampe.put("numpagine", Integer.parseInt(item.getString()));
            } else if (item.isFormField() && fname.equals("anno_pub") && !item.getString().isEmpty()) {
                ristampe.put("datapub", item.getString());
            } else if (item.isFormField() && fname.equals("editore") && !item.getString().isEmpty()) {
                ristampe.put("editore", item.getString());
            } else if (item.isFormField() && fname.equals("lingua") && !item.getString().isEmpty()) {
                ristampe.put("lingua", item.getString());
            } else if (item.isFormField() && fname.equals("indice") && !item.getString().isEmpty()) {
                ristampe.put("indice", item.getString());
            } else if (item.isFormField() && fname.equals("keyword") && !item.getString().isEmpty()) {
                keyword.put("tag1", item.getString());
            } else if (item.isFormField() && fname.equals("keyword2") && !item.getString().isEmpty()) {
                keyword.put("tag2", item.getString());
            } else if (item.isFormField() && fname.equals("keyword3") && !item.getString().isEmpty()) {
                keyword.put("tag3", item.getString());
            } else if (item.isFormField() && fname.equals("idkey") && !item.getString().isEmpty()) {
                keyword.put("id", item.getString());
            } else if (item.isFormField() && fname.equals("idpub") && !item.getString().isEmpty()) {
                pub.put("id", item.getString());
            } else if (item.isFormField() && fname.equals("idris") && !item.getString().isEmpty()) {
                ristampe.put("isbn", item.getString());
            } else if (item.isFormField() && fname.equals("modifica") && !item.getString().isEmpty()) {
                storyboard.put("descrizione_modifica", item.getString());
            } else if (!item.isFormField() && fname.equals("PDF")) {
                String name = item.getName();
                long size = item.getSize();
                if (size > 0 && !name.isEmpty()) {
                    File target = new File(getServletContext().getRealPath("") + File.separatorChar + "PDF"
                            + File.separatorChar + name);
                    item.write(target);
                    ristampe.put("download", "PDF" + File.separatorChar + name);
                }
            } else if (!item.isFormField() && fname.equals("copertina")) {
                String name = item.getName();
                long size = item.getSize();
                if (size > 0 && !name.isEmpty()) {
                    File target = new File(getServletContext().getRealPath("") + File.separatorChar
                            + "Copertine" + File.separatorChar + name);
                    item.write(target);
                    ristampe.put("copertina", "Copertine" + File.separatorChar + name);
                }
            }
        }

        storyboard.put("id_utente", s.getAttribute("userid"));
        storyboard.put("id_pub", pub.get("id"));

        if (Database.updateRecord("keyword", keyword, "id=" + keyword.get("id"))) {

            Database.updateRecord("pubblicazioni", pub, "id=" + pub.get("id"));
            Database.insertRecord("storyboard", storyboard);
            Database.updateRecord("ristampe", ristampe, "isbn=" + ristampe.get("isbn"));

            return true;
        } else {
            return false;
        }
    }
    return false;
}

From source file:kotys.monika.MenuCreatorJSP.LoadData.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from   ww w. j  a  va 2 s  . c  om
 * @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 {
    // Check that we have a file upload request
    request.setCharacterEncoding("UTF-8");
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    ArrayList<String> files = new ArrayList<String>();

    if (!isMultipart) {
        return;
    }

    // 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(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")));

    // constructs the folder where uploaded file will be stored
    String uploadFolder = getServletContext().getRealPath("") + File.separator + DATA_DIRECTORY;

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);

    // Set overall request size constraint
    upload.setSizeMax(MAX_REQUEST_SIZE);

    try {
        // Parse the request
        List items = upload.parseRequest(request);
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            if (!item.isFormField()) {
                String fileName = new File(item.getName()).getName();
                String filePath = uploadFolder + File.separator + fileName;
                File uploadedFile = new File(filePath);
                System.out.println(filePath);
                // saves the file to upload directory
                item.write(uploadedFile);
                files.add(filePath);
            }
        }

        // displays done.jsp page after upload finished
        request.getSession().setAttribute("uploadedFiles", files);
        processRequest(request, response);

    } catch (FileUploadException ex) {
        throw new ServletException(ex);
    } catch (Exception ex) {
        Logger.getLogger(LoadData.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.liferay.util.servlet.UploadServletRequest.java

public UploadServletRequest(HttpServletRequest req) throws IOException {

    super(req);/*from   w  ww  .  j av  a2 s  . c om*/

    _params = new LinkedHashMap();

    try {
        //DiskFileUpload diskFileUpload = new DiskFileUpload(
        //   new LiferayFileItemFactory(DEFAULT_TEMP_DIR));

        ServletFileUpload diskFileUpload = new LiferayDiskFileUpload(
                new LiferayFileItemFactory(DEFAULT_TEMP_DIR), req);

        diskFileUpload.setSizeMax(DEFAULT_SIZE_MAX);

        List list = diskFileUpload.parseRequest(req);

        for (int i = 0; i < list.size(); i++) {
            LiferayFileItem fileItem = (LiferayFileItem) list.get(i);

            if (fileItem.isFormField()) {
                fileItem.setString(req.getCharacterEncoding());
            }

            LiferayFileItem[] fileItems = (LiferayFileItem[]) _params.get(fileItem.getFieldName());

            if (fileItems == null) {
                fileItems = new LiferayFileItem[] { fileItem };
            } else {
                LiferayFileItem[] newFileItems = new LiferayFileItem[fileItems.length + 1];

                System.arraycopy(fileItems, 0, newFileItems, 0, fileItems.length);

                newFileItems[newFileItems.length - 1] = fileItem;

                fileItems = newFileItems;
            }

            _params.put(fileItem.getFieldName(), fileItems);
            if (fileItem.getFileName() != null)
                _params.put(fileItem.getFileName(), new LiferayFileItem[] { fileItem });

        }
    } catch (FileUploadException fue) {
        Logger.error(this, fue.getMessage(), fue);
    }
}

From source file:gov.nih.nci.caadapter.ws.AddNewScenario.java

/** **********************************************************
 *  doPost()/*from w  w  w .  j  av a  2 s. co m*/
 ************************************************************ */
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    try {
        /* disable security for caAdatper 4.3 release 03-31-2009
         HttpSession session = req.getSession(false);
                
          if(session==null)
          {
          res.sendRedirect("/caAdapterWS/login.do");
          return;
          }
                
          String user = (String) session.getAttribute("userid");
          System.out.println(user);
          AbstractSecurityDAO abstractDao= DAOFactory.getDAO();
          SecurityAccessIF getSecurityAccess = abstractDao.getSecurityAccess();
          Permissions perm = getSecurityAccess.getUserObjectPermssions(user, 1);
          System.out.println(perm);
          if (!perm.getCreate()){
          System.out.println("No create Permission for user" + user);
          res.sendRedirect("/caAdapterWS/permissionmsg.do");
          return;
          }
          */
        String name = "EMPTY";

        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Parse the request
        List /* FileItem */ items = upload.parseRequest(req);

        // Process the uploaded items
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            if (item.isFormField()) {
                if (item.getFieldName().equals("MSName")) {
                    MSName = item.getString();
                    path = System.getProperty("gov.nih.nci.caadapter.path");
                    if (path == null)
                        path = ScenarioUtil.SCENARIO_HOME;
                    File scnHome = new File(path);
                    if (!scnHome.exists())
                        scnHome.mkdir();
                    path = path + "/";
                    System.out.println(path);
                    boolean exists = (new File(path + MSName)).exists();
                    if (exists) {
                        System.out.println("Scenario exists, overwriting ... ...");
                        String errMsg = "Scenario exists, not able to save:" + MSName;
                        req.setAttribute("rtnMessage", errMsg);
                        res.sendRedirect("/caAdapterWS/errormsg.do");
                        return;
                    } else {
                        boolean success = (new File(path + MSName)).mkdir();
                        if (!success) {
                            System.out.println("New scenario, Creating ... ...");
                        }
                    }

                }
            } else {
                System.out.println(item.getFieldName());
                name = item.getFieldName();

                String filePath = item.getName();
                String fileName = extractOriginalFileName(filePath);
                System.out.println("AddNewScenario.doPost()..original file Name:" + fileName);
                if (fileName == null || fileName.equals(""))
                    continue;
                String uploadedFilePath = path + MSName + "/" + fileName;
                System.out.println("AddNewScenario.doPost()...write data to file:" + uploadedFilePath);
                File uploadedFile = new File(uploadedFilePath);
                if (name.equals("mappingFileName")) {
                    String uploadedMapBak = uploadedFilePath + ".bak";
                    //write bak of Mapping file
                    item.write(new File(uploadedMapBak));
                    updateMapping(uploadedMapBak);
                } else
                    item.write(uploadedFile);
            }
        }
        ScenarioUtil.addNewScenarioRegistration(MSName);
        res.sendRedirect("/caAdapterWS/success.do");

    } catch (NullPointerException ne) {
        System.out.println("Error in doPost: " + ne);
        req.setAttribute("rtnMessage", ne.getMessage());
        res.sendRedirect("/caAdapterWS/errormsg.do");
    } catch (Exception e) {
        System.out.println("Error in doPost: " + e);
        req.setAttribute("rtnMessage", e.getMessage());
        res.sendRedirect("/caAdapterWS/error.do");
    }
}

From source file:it.lufraproini.cms.servlet.upload_user_img.java

private Map prendiInfoFile(HttpServletRequest request) throws ErroreGrave, IOException {
    Map infofile = new HashMap();
    //riutilizzo codice prof. Della Penna per l'upload
    if (ServletFileUpload.isMultipartContent(request)) {
        // Funzioni delle librerie Apache per l'upload
        try {/*from w  ww.jav a2 s  .c  o  m*/
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items;
            FileItem file = null;

            items = upload.parseRequest(request);
            for (FileItem item : items) {
                String name = item.getFieldName();
                if (name.equals("file_to_upload")) {
                    file = item;
                    break;
                }
            }
            if (file == null || file.getName().equals("")) {
                throw new ErroreGrave("la form non ha inviato il campo file!");
            } else {
                //informazioni
                String nome_e_path = file.getName();
                String estensione = FilenameUtils.getExtension(FilenameUtils.getName(nome_e_path));
                String nome_senza_estensione = FilenameUtils.getBaseName(FilenameUtils.getName(nome_e_path));
                infofile.put("nome_completo", nome_senza_estensione + "." + estensione);
                infofile.put("estensione", estensione);
                infofile.put("nome_senza_estensione", nome_senza_estensione);
                infofile.put("dimensione", file.getSize());
                infofile.put("input_stream", file.getInputStream());
                infofile.put("content_type", file.getContentType());
            }

        } catch (FileUploadException ex) {
            Logger.getLogger(upload_user_img.class.getName()).log(Level.SEVERE, null, ex);
            throw new ErroreGrave("errore libreria apache!");
        }

    }
    return infofile;
}

From source file:com.gae.ImageUpServlet.java

public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    //DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
    //ReturnValue value = new ReturnValue();
    MemoryFileItemFactory factory = new MemoryFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    resp.setContentType("image/jpeg");
    ServletOutputStream out = resp.getOutputStream();
    try {/*  ww w  .j a v a 2 s  . co  m*/
        List<FileItem> list = upload.parseRequest(req);
        //FileItem list = upload.parseRequest(req);
        for (FileItem item : list) {
            if (!(item.isFormField())) {
                filename = item.getName();
                if (filename != null && !"".equals(filename)) {
                    int size = (int) item.getSize();
                    byte[] data = new byte[size];
                    InputStream in = item.getInputStream();
                    in.read(data);
                    ImagesService imagesService = ImagesServiceFactory.getImagesService();
                    Image newImage = ImagesServiceFactory.makeImage(data);
                    byte[] newImageData = newImage.getImageData();

                    //imgkey = KeyFactory.createKey(Imagedat.class.getSimpleName(), filename.split(".")[0]);   
                    //imgkey = KeyFactory.createKey(Imagedat.class.getSimpleName(), filename.split(".")[0]);   

                    out.write(newImageData);
                    out.flush();

                    DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
                    Key key = KeyFactory.createKey(kind, skey);
                    Blob blobImage = new Blob(newImageData);
                    DirectBeans_textjson dbeans = new DirectBeans_textjson();
                    /*  ?Date?     */
                    //Entity entity = dbeans.setentity("add", kind, true, key, id, val);

                    //ReturnValue value = dbeans.Called.setentity("add", kind, true, key, id, val);
                    //Entity entity = value.entity;
                    //DirectBeans.ReturnValue value = new DirectBeans.ReturnValue();
                    DirectBeans_textjson.entityVal eval = dbeans.setentity("add", kind, true, key, id, val);
                    Entity entity = eval.entity;

                    /*  ?Date                         */
                    //for(int i=0; i<id.length; i++ ){
                    //   if(id[i].equals("image")){
                    //      //filetitle = val[i];
                    //      //imgkey = KeyFactory.createKey(Imagedat.class.getSimpleName(), val[i]);   
                    //   }
                    //}                

                    entity.setProperty("image", blobImage);
                    Date date = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd:HHmmss");
                    sdf.setTimeZone(TimeZone.getTimeZone("JST"));
                    entity.setProperty("moddate", sdf.format(date));
                    //DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
                    ds.put(entity);
                    out.println("? KEY:" + key);
                }
            }
        }
    } catch (FileUploadException e) {
        e.printStackTrace();
    } finally {
        if (out != null) {
            out.close();
        }
    }
}

From source file:com.flaptor.clusterfest.deploy.DeployModule.java

@SuppressWarnings("unchecked")
public String doPage(String page, HttpServletRequest request, HttpServletResponse response) {
    List<NodeDescriptor> nodes = new ArrayList<NodeDescriptor>();
    String[] nodesParam = request.getParameterValues("node");
    if (nodesParam != null) {
        for (String idx : nodesParam) {
            nodes.add(ClusterManager.getInstance().getNodes().get(Integer.parseInt(idx)));
        }//  ww w . ja  va 2s. co  m
    }
    request.setAttribute("nodes", nodes);

    if (ServletFileUpload.isMultipartContent(request)) {
        // Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        String name = null;
        byte[] content = null;
        String path = null;
        // Parse the request
        try {
            List<FileItem> items = upload.parseRequest(request);
            String message = "";
            for (FileItem item : items) {
                String fieldName = item.getFieldName();
                if (fieldName.equals("node")) {
                    NodeDescriptor node = ClusterManager.getInstance().getNodes()
                            .get(Integer.parseInt(item.getString()));
                    if (!node.isReachable())
                        message += node + " is unreachable<br/>";
                    if (getModuleNode(node) != null)
                        nodes.add(node);
                    else
                        message += node + " is not registered as deployable<br/>";
                }
                if (fieldName.equals("path"))
                    path = item.getString();

                if (fieldName.equals("file")) {
                    name = item.getName();
                    content = IOUtil.readAllBinary(item.getInputStream());
                }
            }
            List<Pair<NodeDescriptor, Throwable>> errors = deployFiles(nodes, path, name, content);
            if (errors != null && errors.size() > 0) {
                request.setAttribute("deployCorrect", false);
                request.setAttribute("deployErrors", errors);
            } else
                request.setAttribute("deployCorrect", true);
            request.setAttribute("message", message);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    return "deploy.vm";
}

From source file:gsn.http.FieldUpload.java

public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    String msg;/*from   w w  w  .  j  ava  2s  .co m*/
    Integer code;
    PrintWriter out = res.getWriter();
    ArrayList<String> paramNames = new ArrayList<String>();
    ArrayList<String> paramValues = new ArrayList<String>();

    //Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(req);
    if (!isMultipart) {
        out.write("not multipart!");
        code = 666;
        msg = "Error post data is not multipart!";
        logger.error(msg);
    } else {
        // Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Set overall request size constraint
        upload.setSizeMax(5 * 1024 * 1024);

        List items;
        try {
            // Parse the request
            items = upload.parseRequest(req);

            //building xml data out of the input
            String cmd = "";
            String vsname = "";
            Base64 b64 = new Base64();
            StringBuilder sb = new StringBuilder("<input>\n");
            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.getFieldName().equals("vsname")) {
                    //define which cmd block is sent
                    sb.append("<vsname>" + item.getString() + "</vsname>\n");
                    vsname = item.getString();
                } else if (item.getFieldName().equals("cmd")) {
                    //define which cmd block is sent
                    cmd = item.getString();
                    sb.append("<command>" + item.getString() + "</command>\n");
                    sb.append("<fields>\n");
                } else if (item.getFieldName().split(";")[0].equals(cmd)) {
                    //only for the defined cmd       
                    sb.append("<field>\n");
                    sb.append("<name>" + item.getFieldName().split(";")[1] + "</name>\n");
                    paramNames.add(item.getFieldName().split(";")[1]);
                    if (item.isFormField()) {
                        sb.append("<value>" + item.getString() + "</value>\n");
                        paramValues.add(item.getString());
                    } else {
                        sb.append("<value>" + new String(b64.encode(item.get())) + "</value>\n");
                        paramValues.add(new String(b64.encode(item.get())));
                    }
                    sb.append("</field>\n");
                }
            }
            sb.append("</fields>\n");
            sb.append("</input>\n");

            //do something with xml aka statement.toString()

            AbstractVirtualSensor vs = null;
            try {
                vs = Mappings.getVSensorInstanceByVSName(vsname).borrowVS();
                vs.dataFromWeb(cmd, paramNames.toArray(new String[] {}),
                        paramValues.toArray(new Serializable[] {}));
            } catch (VirtualSensorInitializationFailedException e) {
                logger.warn("Sending data back to the source virtual sensor failed !: " + e.getMessage(), e);
            } finally {
                Mappings.getVSensorInstanceByVSName(vsname).returnVS(vs);
            }

            code = 200;
            msg = "The upload to the virtual sensor went successfully! (" + vsname + ")";
        } catch (ServletFileUpload.SizeLimitExceededException e) {
            code = 600;
            msg = "Upload size exceeds maximum limit!";
            logger.error(msg, e);
        } catch (Exception e) {
            code = 500;
            msg = "Internal Error: " + e;
            logger.error(msg, e);
        }

    }
    //callback to the javascript
    out.write("<script>window.parent.GSN.msgcallback('" + msg + "'," + code + ");</script>");
}

From source file:com.ikon.servlet.admin.MimeTypeServlet.java

@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doPost({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    String action = WebUtils.getString(request, "action");
    String userId = request.getRemoteUser();
    Session dbSession = null;//from   w ww  . ja v  a 2  s.  c  o m
    updateSessionManager(request);

    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            InputStream is = null;
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);
            MimeType mt = new MimeType();
            byte data[] = null;

            for (Iterator<FileItem> it = items.iterator(); it.hasNext();) {
                FileItem item = it.next();

                if (item.isFormField()) {
                    if (item.getFieldName().equals("action")) {
                        action = item.getString("UTF-8");
                    } else if (item.getFieldName().equals("mt_id")) {
                        mt.setId(Integer.parseInt(item.getString("UTF-8")));
                    } else if (item.getFieldName().equals("mt_name")) {
                        mt.setName(item.getString("UTF-8").toLowerCase());
                    } else if (item.getFieldName().equals("mt_extensions")) {
                        String[] extensions = item.getString("UTF-8").split(" ");
                        for (int i = 0; i < extensions.length; i++) {
                            mt.getExtensions().add(extensions[i].toLowerCase());
                        }
                    }
                } else {
                    is = item.getInputStream();
                    data = IOUtils.toByteArray(is);
                    mt.setImageMime(MimeTypeConfig.mimeTypes.getContentType(item.getName()));
                    is.close();
                }
            }

            if (action.equals("create")) {
                // Because this servlet is also used for SQL import and in that case I don't
                // want to waste a b64Encode conversion. Call it a sort of optimization.
                mt.setImageContent(SecureStore.b64Encode(data));
                long id = MimeTypeDAO.create(mt);
                MimeTypeConfig.loadMimeTypes();

                // Activity log
                UserActivity.log(userId, "ADMIN_MIME_TYPE_CREATE", Long.toString(id), null, mt.toString());
                list(userId, request, response);
            } else if (action.equals("edit")) {
                // Because this servlet is also used for SQL import and in that case I don't
                // want to waste a b64Encode conversion. Call it a sort of optimization.
                mt.setImageContent(SecureStore.b64Encode(data));
                MimeTypeDAO.update(mt);
                MimeTypeConfig.loadMimeTypes();

                // Activity log
                UserActivity.log(userId, "ADMIN_MIME_TYPE_EDIT", Long.toString(mt.getId()), null,
                        mt.toString());
                list(userId, request, response);
            } else if (action.equals("delete")) {
                MimeTypeDAO.delete(mt.getId());
                MimeTypeConfig.loadMimeTypes();

                // Activity log
                UserActivity.log(userId, "ADMIN_MIME_TYPE_DELETE", Long.toString(mt.getId()), null, null);
                list(userId, request, response);
            } else if (action.equals("import")) {
                dbSession = HibernateUtil.getSessionFactory().openSession();
                importMimeTypes(userId, request, response, data, dbSession);
                list(userId, request, response);
            }
        }
    } catch (DatabaseException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (FileUploadException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (SQLException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } finally {
        HibernateUtil.close(dbSession);
    }
}

From source file:com.controller.RecipeImage.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   ww  w  .  j av  a2  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 {
    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);
    }
}