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

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

Introduction

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

Prototype

public ServletFileUpload(FileItemFactory fileItemFactory) 

Source Link

Document

Constructs an instance of this class which uses the supplied factory to create FileItem instances.

Usage

From source file:fr.gael.dhus.server.http.webapp.api.controller.UploadController.java

@PreAuthorize("hasRole('ROLE_UPLOAD')")
@RequestMapping(value = "/upload", method = { RequestMethod.POST })
public void upload(Principal principal, HttpServletRequest req, HttpServletResponse res) throws IOException {
    // process only multipart requests
    if (ServletFileUpload.isMultipartContent(req)) {
        // 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
        try {/*w ww . j  av  a  2  s  . co  m*/
            ArrayList<String> collectionIds = new ArrayList<>();
            FileItem product = null;

            List<FileItem> items = upload.parseRequest(req);
            for (FileItem item : items) {
                if (COLLECTIONSKEY.equals(item.getFieldName())) {
                    if (item.getString() != null && !item.getString().isEmpty()) {
                        for (String cid : item.getString().split(",")) {
                            collectionIds.add(cid);
                        }
                    }
                } else if (PRODUCTKEY.equals(item.getFieldName())) {
                    product = item;
                }
            }
            if (product == null) {
                res.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "Your request is missing a product file to upload.");
                return;
            }
            productUploadService.upload(product, collectionIds);
            res.setStatus(HttpServletResponse.SC_CREATED);
            res.getWriter().print("The file was created successfully.");
            res.flushBuffer();
        } catch (FileUploadException e) {
            LOGGER.error("An error occurred while parsing request.", e);
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while parsing request : " + e.getMessage());
        } catch (UserNotExistingException e) {
            LOGGER.error("You need to be connected to upload a product.", e);
            res.sendError(HttpServletResponse.SC_UNAUTHORIZED, "You need to be connected to upload a product.");
        } catch (UploadingException e) {
            LOGGER.error("An error occurred while uploading the product.", e);
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while uploading the product : " + e.getMessage());
        } catch (RootNotModifiableException e) {
            LOGGER.error("An error occurred while uploading the product.", e);
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while uploading the product : " + e.getMessage());
        } catch (ProductNotAddedException e) {
            LOGGER.error("Your product can not be read by the system.", e);
            res.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Your product can not be read by the system.");
        }
    } else {
        res.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
                "Request contents type is not supported by the servlet.");
    }
}

From source file:check_reg_bidder.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    try {/*  w ww . j  ava2s  .c  o m*/

        HttpSession sess = request.getSession(true);
        String f = (String) sess.getAttribute("fn");
        String l = (String) sess.getAttribute("ln");
        String mail = (String) sess.getAttribute("em");
        String un = (String) sess.getAttribute("usr");
        String pwd = (String) sess.getAttribute("pass");
        String add = (String) sess.getAttribute("add");
        String phn = (String) sess.getAttribute("no");
        String cit = (String) sess.getAttribute("city");
        String ut = (String) sess.getAttribute("type");
        String des = (String) sess.getAttribute("des");
        String dept = (String) sess.getAttribute("depa");

        //            out.println(dept);

        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/project?zeroDateTimeBehavior=convertToNull", "root", "root");
        Statement st = con.createStatement();

        boolean isMultipart = ServletFileUpload.isMultipartContent(request);//retrive req.. data & extract below
        //out.println(isMultipart);
        if (isMultipart) {

            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List items = upload.parseRequest(request);
            String paraname[] = new String[15];
            int i = 0;
            Iterator iterator = items.iterator();

            while (iterator.hasNext()) {
                org.apache.commons.fileupload.FileItem item = (org.apache.commons.fileupload.FileItem) iterator
                        .next();
                paraname[i] = item.getString();// one by one tag's values to arrat

                //out.println(i+"----"+paraname[i]);
                //out.println("<br>");
                i++;
                if (!item.isFormField())// if type=file
                {
                    String fileName = item.getName();// uploadiing file
                    out.println(fileName);
                    String root = "D:\\rushiraj\\Main Project\\web";//currnet path
                    File path = new File(root + "/cmpfile");// path plus testimage directory
                    if (!path.exists()) {
                        boolean status = path.mkdirs(); //if dir! not exists than createe once
                    }
                    File uploadedFile = new File(path + "/" + fileName); /// upload file/image  at path

                    item.write(uploadedFile);//phiscaly write-
                    String q1 = "insert into company_details (name,pan_no,it_cer,est_date,lic_val,reg_no,address,city,state,class) values('"
                            + paraname[0] + "','" + paraname[1] + "','" + fileName + "','" + paraname[2] + "','"
                            + paraname[3] + "','" + paraname[4] + "','" + paraname[5] + paraname[6]
                            + paraname[7] + "','" + paraname[8] + "','" + paraname[9] + "','" + paraname[10]
                            + "')";
                    String query = "insert into register (first_name,last_name,mail,username,password,phone,address,city,type,designation,department) values('"
                            + f + "','" + l + "','" + mail + "','" + un + "','" + pwd + "','" + phn + "','"
                            + add + "','" + cit + "','" + ut + "','" + des + "','" + dept + "');";
                    out.println(q1);
                    out.println(query);
                    int r = st.executeUpdate(q1);//insert remaing data into table.....
                    int p = st.executeUpdate(query);

                    if (r > 0) {
                        response.sendRedirect("login.jsp");
                    }
                }
            }
        }
    } catch (Exception ex) {
        out.println(ex);
    }

}

From source file:emsa.webcoc.cleanup.servlet.UploadServet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//  w ww  .  jav 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 {

    isMultipart = ServletFileUpload.isMultipartContent(request);
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    if (!isMultipart) {
        out.println("<html>");
        out.println("<head>");
        out.println("<title>XML file clean up</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 into memory
    factory.setSizeThreshold(MAXMEMSIZE);
    //Path to save file if its size is bigger than MAXMEMSIZE
    factory.setRepository(new File(REPOSITORY));
    ServletFileUpload upload = new ServletFileUpload(factory);

    out.println("<html>");
    out.println("<head>");
    out.println("<title>XML file clean up</title>");
    out.println("</head>");
    out.println("<body>");

    try {
        List<FileItem> fileItems = upload.parseRequest(request);
        Iterator<FileItem> t = fileItems.iterator();

        while (t.hasNext()) {
            FileItem f = t.next();

            if (!f.isFormField()) {
                if (f.getContentType().equals("text/xml")) { //Check weather or not the uploaded file is an XML file

                    String uniqueFileName = f.getName() + "-" + request.getSession().getId() + ".xml"; //Creates unique name
                    String location = (String) this.getServletContext().getAttribute("newFileLocation");

                    CoCCleanUp clean = new CoCCleanUp(uniqueFileName, location);

                    if (clean.cleanDocument(f.getInputStream()) == 0) {
                        out.println("<h3>" + f.getName() + " was clean</h3>");
                        out.println(clean.printHTMLStatistics());
                        out.println("<br /><form action='download?filename=" + uniqueFileName
                                + "' method='post'><input type='submit' value='Download'/></form></body></html>");
                    } else {
                        out.println("<h3>" + clean.getErrorMessage() + "</h3>");
                        out.println(
                                "<br /><form action='index.html' method='post'><input type='submit' value='Go Back'/></form></body></html>");
                    }
                } else {
                    out.println("<h3>The file " + f.getName() + " is not an xml file</h3>");
                    out.println(
                            "<br /><form action='index.html' method='post'><input type='submit' value='Go Back'/></form></body></html>");
                    logger.warn("The file " + f.getName() + " is not an xml file: " + f.getContentType());
                }
            }
        }

        File repository = factory.getRepository();
        cleanTmpFiles(repository);

    } catch (IOException | FileUploadException e) {
        out.println("<h3>Something went wrong</h3></br>");
        out.println(
                "<br /><form action='index.html' method='post'><input type='submit' value='Go Back'/></form></body></html>");
    }
}

From source file:com.controller.RecipeImage.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  w w w. ja  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 {
    response.setContentType("text/html;charset=UTF-8");

    //retrieving the path to store image from web.xml
    filePath = getServletContext().getInitParameter("recipeImageStorePath");

    //retrieving the path to display image from web.xml
    fileDisplay = getServletContext().getInitParameter("recipeImageDisplayPath");

    // Check that we have a file upload request
    isMultipart = ServletFileUpload.isMultipartContent(request);
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    if (!isMultipart) {
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<p>No file uploaded</p>");
        out.println("</body>");
        out.println("</html>");
        return;
    }
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(maxMemSize);
    // Location to save data that is larger than maxMemSize.
    factory.setRepository(new File("c:\\temp"));

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum file size to be uploaded.
    upload.setSizeMax(maxFileSize);

    try {
        // Parse the request to get file items.
        List fileItems = upload.parseRequest(request);

        // Process the uploaded file items
        Iterator i = fileItems.iterator();

        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("1");
        while (i.hasNext()) {
            out.println("2");
            FileItem fi = (FileItem) i.next();
            if (!fi.isFormField()) {
                // Get the uploaded file parameters
                String fieldName = fi.getFieldName();
                fileName = fi.getName();
                fileName = randomString(fileName);
                String contentType = fi.getContentType();
                boolean isInMemory = fi.isInMemory();
                long sizeInBytes = fi.getSize();
                // Write the file
                if (fileName.lastIndexOf("\\") >= 0) {
                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
                } else {
                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));
                }
                fi.write(file);
                out.println("Uploaded Filename: " + fileName + "<br>" + filePath);
            } else {
                out.println("No file");
            }
        }
        out.println("</body>");
        out.println("</html>");

        RecipeBean recipeBean = new RecipeBean();
        RecipeDAO recipeDAO = new RecipeDAO();

        String image = fileDisplay + "" + fileName;
        out.println(image);

        HttpSession session = request.getSession();
        String recipeId = (String) session.getAttribute("recipeId");
        session.removeAttribute("recipeId");
        recipeDAO.addImage(recipeId, image);

        response.sendRedirect("Home");

    } catch (Exception ex) {
        System.out.println(ex);
    }
}

From source file:admin.controller.ServletAddPersonality.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   w w w  .ja  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
 */
public void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    super.processRequest(request, response);
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    File file;
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    try {

        String uploadPath = AppConstants.BRAND_IMAGES_HOME;

        // Verify the content type
        String contentType = request.getContentType();
        if ((contentType.indexOf("multipart/form-data") >= 0)) {

            DiskFileItemFactory factory = new DiskFileItemFactory();
            // maximum size that will be stored in memory
            factory.setSizeThreshold(maxMemSize);
            // Location to save data that is larger than maxMemSize.
            factory.setRepository(new File("/tmp"));

            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            // maximum file size to be uploaded.
            upload.setSizeMax(maxFileSize);

            // Parse the request to get file items.
            List fileItems = upload.parseRequest(request);

            // Process the uploaded file items
            Iterator i = fileItems.iterator();

            out.println("<html>");
            out.println("<head>");
            out.println("<title>JSP File upload</title>");
            out.println("</head>");
            out.println("<body>");
            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (fi.isFormField()) {
                    // Get the uploaded file parameters
                    field_name = fi.getFieldName();
                    if (field_name.equals("brandname")) {
                        brand_name = fi.getString();
                    }
                    if (field_name.equals("look")) {
                        look_id = fi.getString();
                    }

                } else {
                    check = brand.checkAvailability(brand_name);

                    if (check == false) {
                        field_name = fi.getFieldName();
                        file_name = fi.getName();

                        File uploadDir = new File(uploadPath);
                        if (!uploadDir.exists()) {
                            uploadDir.mkdirs();
                        }

                        //                                int inStr = file_name.indexOf(".");
                        //                                String Str = file_name.substring(0, inStr);
                        //                                file_name = brand_name + "_" + Str + ".jpeg";

                        file_name = brand_name + "_" + file_name;
                        boolean isInMemory = fi.isInMemory();
                        long sizeInBytes = fi.getSize();

                        String filePath = uploadPath + File.separator + file_name;
                        File storeFile = new File(filePath);

                        fi.write(storeFile);
                        brand.addBrands(brand_name, Integer.parseInt(look_id), file_name);

                        response.sendRedirect(request.getContextPath() + "/admin/brandpersonality.jsp");

                        out.println("Uploaded Filename: " + filePath + "<br>");
                    } else {
                        response.sendRedirect(
                                request.getContextPath() + "/admin/brandpersonality.jsp?exist=exist");
                    }
                }
            }
            out.println("</body>");
            out.println("</html>");
        } else {
            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>");
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "", ex);
    } finally {
        try {
            out.close();
        } catch (Exception e) {
            logger.log(Level.SEVERE, "", e);
        }
    }

}

From source file:com.sapuraglobal.hrms.servlet.UploadEmp.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  w ww. j ava2s .  co  m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    String action = request.getParameter("action");
    System.out.println("action: " + action);
    if (action == null || action.isEmpty()) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        //PriceDAO priceDAO = new PriceDAO();

        try {
            List<FileItem> fields = upload.parseRequest(request);
            //out.println("Number of fields: " + fields.size() + "<br/><br/>");
            Iterator<FileItem> it = fields.iterator();
            while (it.hasNext()) {
                FileItem fileItem = it.next();
                //store in webserver.
                String fileName = fileItem.getName();
                if (fileName != null) {
                    File file = new File(fileName);
                    fileItem.write(file);
                    System.out.println("File successfully saved as " + file.getAbsolutePath());

                    //process file
                    Reader in = new FileReader(file.getAbsolutePath());
                    Iterable<CSVRecord> records = CSVFormat.EXCEL.withHeader().parse(in);
                    for (CSVRecord record : records) {
                        String name = record.get("<name>");
                        String login = record.get("<login>");
                        String title = record.get("<title>");
                        String email = record.get("<email>");
                        String role = record.get("<role>");
                        String dept = record.get("<department>");
                        String joinDate = record.get("<joinDate>");
                        String probDate = record.get("<probDate>");
                        String annLeaveEnt = record.get("<leave_entitlement>");
                        String annBal = record.get("<leave_bal>");
                        String annMax = record.get("<leave_max>");
                        String annCF = record.get("<leave_cf>");
                        String med = record.get("<med_taken>");
                        String oil = record.get("<oil_taken>");
                        String unpaid = record.get("<unpaid_taken>");
                        String child = record.get("<child_bal>");

                        TitleDTO titleDto = titleBean.getTitleByName(title);
                        RoleDTO roleDto = accessBean.getRole(role);
                        DeptDTO deptDto = deptBean.getDepartment(dept);
                        //create the user first
                        UserDTO user = new UserDTO();
                        user.setName(name);
                        user.setLogin(login);
                        user.setTitle(titleDto);
                        user.setEmail(email);
                        user.setDateJoin(Utility.format(joinDate, "dd/MM/yyyy"));
                        user.setProbationDue(Utility.format(probDate, "dd/MM/yyyy"));
                        //store in user table.
                        userBean.createUser(user);
                        //assign role
                        userBean.assignRole(user, roleDto);
                        //assign dept
                        deptBean.assignEmployee(user, deptDto);

                        //leave ent
                        LeaveTypeDTO lvtypeDTO = leaveBean.getLeaveType("Annual");
                        LeaveEntDTO annualentDTO = new LeaveEntDTO();
                        annualentDTO.setCurrent(Double.parseDouble(annLeaveEnt));
                        annualentDTO.setBalance(Double.parseDouble(annBal));
                        annualentDTO.setMax(Double.parseDouble(annMax));
                        annualentDTO.setCarriedOver(Double.parseDouble(annCF));
                        annualentDTO.setLeaveType(lvtypeDTO);
                        //assign annual leave
                        annualentDTO.setUser(user);
                        leaveBean.addLeaveEnt(annualentDTO);
                        //medical ent
                        LeaveTypeDTO medTypeDTO = leaveBean.getLeaveType("Medical Leave");
                        LeaveEntDTO medentDTO = new LeaveEntDTO();
                        medentDTO.setBalance(medTypeDTO.getDays() - Double.parseDouble(med));
                        medentDTO.setCurrent(medTypeDTO.getDays());
                        medentDTO.setUser(user);
                        medentDTO.setLeaveType(medTypeDTO);
                        leaveBean.addLeaveEnt(medentDTO);
                        //oil ent
                        LeaveTypeDTO oilTypeDTO = leaveBean.getLeaveType("Off-in-Lieu");
                        LeaveEntDTO oilentDTO = new LeaveEntDTO();
                        oilentDTO.setBalance(oilTypeDTO.getDays() - Double.parseDouble(oil));
                        oilentDTO.setCurrent(0);
                        oilentDTO.setUser(user);
                        oilentDTO.setLeaveType(oilTypeDTO);
                        leaveBean.addLeaveEnt(oilentDTO);
                        //unpaid
                        LeaveTypeDTO unpaidTypeDTO = leaveBean.getLeaveType("Unpaid");
                        LeaveEntDTO unpaidentDTO = new LeaveEntDTO();
                        unpaidentDTO.setBalance(unpaidTypeDTO.getDays() - Double.parseDouble(unpaid));
                        unpaidentDTO.setCurrent(0);
                        unpaidentDTO.setUser(user);
                        unpaidentDTO.setLeaveType(unpaidTypeDTO);
                        leaveBean.addLeaveEnt(unpaidentDTO);
                        //child
                        LeaveTypeDTO childTypeDTO = leaveBean.getLeaveType("Child Care");
                        double cur = childTypeDTO.getDays();
                        LeaveEntDTO childentDTO = new LeaveEntDTO();
                        childentDTO.setBalance(cur - Double.parseDouble(child));
                        childentDTO.setCurrent(cur);
                        childentDTO.setUser(user);
                        childentDTO.setLeaveType(childTypeDTO);
                        leaveBean.addLeaveEnt(childentDTO);

                    }
                    /*
                    if (stockPrices.size() > 0) {
                       priceDAO.OpenConnection();
                       priceDAO.updateStockPrice(stockPrices);
                    }
                                */

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            //priceDAO.CloseConnection();
            RequestDispatcher dispatcher = request.getRequestDispatcher("/employee");
            //request.setAttribute(Constants.TITLE, "Home");
            dispatcher.forward(request, response);
        }
    } else {
        RequestDispatcher dispatcher = request.getRequestDispatcher("/uploadEmp.jsp");
        //request.setAttribute(Constants.TITLE, "Home");
        dispatcher.forward(request, response);

    }
}

From source file:cn.clxy.studio.common.web.multipart.GMultipartResolver.java

/**
 * Initialize the underlying//  w  w  w  . j  a v a 2s.c  om
 * <code>org.apache.commons.fileupload.servlet.ServletFileUpload</code> instance. Can be
 * overridden to use a custom subclass, e.g. for testing purposes.
 *
 * @param fileItemFactory the Commons FileItemFactory to use
 * @return the new ServletFileUpload instance
 */
@Override
protected FileUpload newFileUpload(FileItemFactory fileItemFactory) {
    return new ServletFileUpload(fileItemFactory);
}

From source file:attila.core.MultipartRequest.java

@SuppressWarnings("unchecked")
private void readParametersFromRequest(HttpServletRequest request)
        throws FileUploadException, UnsupportedEncodingException {
    textParameters = new HashMap<String, List<String>>();
    binaryParameters = new HashMap<String, FileItem>();
    ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
    List<FileItem> items = upload.parseRequest(request);
    for (FileItem item : items) {
        if (item.isFormField()) {
            readTextParameter(item);/*from   w  ww .j  av  a2  s  .com*/
        } else {
            readBinaryParameter(item);
        }
    }
}

From source file:gsn.http.FieldUpload.java

public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    String msg;/*w w w  .ja va2  s. c  om*/
    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:communicator.doMove.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from ww w. 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 {
    response.setContentType("text/html;charset=UTF-8");

    PrintWriter out = null;
    JSONObject outputObject = new JSONObject();
    try {

        HashMap<String, String> bigItemIds = new HashMap<>();
        Iterator mIterator = bigItemIds.keySet().iterator();
        out = response.getWriter();
        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();

        // Configure a repository (to ensure a secure temp location is used)
        ServletContext servletContext = this.getServletConfig().getServletContext();
        File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
        factory.setRepository(repository);

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        // Parse the request
        List<FileItem> items = upload.parseRequest(request);

        final String moveId = UUID.randomUUID().toString();
        final MovesDb movesDb = new MovesDb();
        // Process the uploaded items
        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = iter.next();

            if (item.isFormField()) {

                System.out.println("Form field" + item.getString());

                bigItemIds = processFormField(new JSONObject(item.getString()), out, moveId, movesDb);
                mIterator = bigItemIds.keySet().iterator();
                System.out.println("ITEM ID SIZE " + bigItemIds.size());

            } else {
                //processUploadedFile(item);
                System.out.print("Photo Field");
                String key = (String) mIterator.next();
                File mFile = new File(bigItemIds.get(key));
                item.write(mFile);

            }
        }
        new Thread() {

            public void run() {
                pushMovetoMailQueue moveToMailQueue = new pushMovetoMailQueue();
                moveToMailQueue.pushMoveToMailQueue(movesDb);
            }
        }.start();
        outputObject = new JSONObject();
        try {
            outputObject.put(Constants.JSON_STATUS, Constants.JSON_SUCCESS);
            outputObject.put(Constants.JSON_MSG, Constants.JSON_GET_QUOTE);
        } catch (JSONException ex1) {
            Logger.getLogger(doSignUp.class.getName()).log(Level.SEVERE, null, ex1);
        }

        out.println(outputObject.toString());

    } catch (Exception ex) {

        outputObject = new JSONObject();
        try {
            outputObject.put(Constants.JSON_STATUS, Constants.JSON_FAILURE);
            outputObject.put(Constants.JSON_MSG, Constants.JSON_EXCEPTION);
        } catch (JSONException ex1) {
            Logger.getLogger(doSignUp.class.getName()).log(Level.SEVERE, null, ex1);
        }

        out.println(outputObject.toString());
        Logger.getLogger(doSignUp.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        out.close();
    }
}