Example usage for org.apache.commons.fileupload FileItem write

List of usage examples for org.apache.commons.fileupload FileItem write

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItem write.

Prototype

void write(File file) throws Exception;

Source Link

Document

A convenience method to write an uploaded item to disk.

Usage

From source file:controller.uploadProductController.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//  w  w  w .j  a v  a 2  s .co  m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpSession session = request.getSession(true);
    String userPath = request.getServletPath();
    if (userPath.equals("/uploadProduct")) {
        boolean success = true;
        // configures upload settings
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // sets memory threshold - beyond which files are stored in disk
        factory.setSizeThreshold(MEMORY_THRESHOLD);
        // sets temporary location to store files
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

        ServletFileUpload upload = new ServletFileUpload(factory);

        // sets maximum size of upload file
        upload.setFileSizeMax(MAX_FILE_SIZE);

        // sets maximum size of request (include file + form data)
        upload.setSizeMax(MAX_REQUEST_SIZE);

        // constructs the directory path to store upload file
        // this path is relative to application's directory
        String uploadPath = getServletContext().getInitParameter("upload.location");
        //creates a HashMap of all inputs
        HashMap hashMap = new HashMap();
        String productId = UUID.randomUUID().toString();
        try {
            @SuppressWarnings("unchecked")
            List<FileItem> formItems = upload.parseRequest(request);
            for (FileItem item : formItems) {
                // processes only fields that are not form fields
                if (!item.isFormField()) {
                    File file = new File(item.getName());
                    File file2 = new File(productId + ".jpg");
                    String filePath = uploadPath + File.separator + file.getName();
                    // saves the file on disk
                    File storeFile = new File(filePath);
                    item.write(storeFile);
                    File rename = new File(filePath);
                    boolean flag = rename.renameTo(file2);
                } else {
                    hashMap.put(item.getFieldName(), item.getString());
                }
            }
        } catch (FileUploadException ex) {
            Logger.getLogger(uploadProductController.class.getName()).log(Level.SEVERE, null, ex);
            request.setAttribute("error", true);
            request.setAttribute("errorMessage", ex.getMessage());
            success = false;
        } catch (Exception ex) {
            Logger.getLogger(uploadProductController.class.getName()).log(Level.SEVERE, null, ex);
            request.setAttribute("error", true);
            request.setAttribute("errorMessage", ex.getMessage());
            success = false;
        }
        String owner = (String) session.getAttribute("customerEmail");
        if (owner == null) {
            owner = "shop";
        }

        String pName = hashMap.get("pName").toString();
        String mNo = hashMap.get("mNo").toString();
        String brand = hashMap.get("brand").toString();
        String description = hashMap.get("description").toString();
        String quantity = hashMap.get("quantity").toString();
        String price = hashMap.get("price").toString();
        String addInfo = hashMap.get("addInfo").toString();
        int categoryId = Integer.parseInt(hashMap.get("category").toString());

        ProductDAO productDAO = new ProductDAOImpl();
        Product product;

        try {
            double priceDouble = Double.parseDouble(price);
            int quantityInt = Integer.parseInt(quantity);
            Category category = (new CategoryDAOImpl()).getCategoryFromID(categoryId);
            if (owner.equals("shop")) {
                product = new Product(productId, pName, mNo, category, quantityInt, priceDouble, brand,
                        description, addInfo, true, true, owner);
            } else {
                product = new Product(productId, pName, mNo, category, quantityInt, priceDouble, brand,
                        description, addInfo, false, false, owner);
            }

            if (!(productDAO.addProduct(product, category.getName()))) {
                throw new Exception("update unsuccessful");
            }
        } catch (Exception e) {
            request.setAttribute("error", true);
            request.setAttribute("errorMessage", e.getMessage());
            success = false;
        }

        request.setAttribute("pName", pName);
        request.setAttribute("mNo", mNo);
        request.setAttribute("brand", brand);
        request.setAttribute("description", description);
        request.setAttribute("quantity", quantity);
        request.setAttribute("price", price);
        request.setAttribute("addInfo", addInfo);
        request.setAttribute("categoryId", categoryId);
        request.setAttribute("success", success);
        if (success == true) {
            request.setAttribute("error", false);
            request.setAttribute("errorMessage", null);
        }
        String url;
        if (owner.equals("shop")) {
            url = "/WEB-INF/view/adminAddProducts.jsp";
        } else {
            url = "/WEB-INF/view/clientSideView/addRecycleProduct.jsp";
        }
        try {
            request.getRequestDispatcher(url).forward(request, response);
        } catch (ServletException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }

}

From source file:com.orange.mmp.context.RequestContext.java

/**
 * Get an uploaded file in current request context (if multipart only) 
 * //from  w ww.  j  a  v a2s.c o m
 * @return A File instance pointing on uploaded file
 */
public List<File> getFiles() throws MMPException {
    List<File> fileList = new ArrayList<File>();
    if (this.isMultipart && this.multipartItems != null) {
        try {

            for (FileItem item : this.multipartItems) {
                if (!item.isFormField()) {
                    File itemFile = new File(System.getProperty("java.io.tmpdir") + "/" + item.getName());
                    item.write(itemFile);
                    fileList.add(itemFile);
                }
            }
        } catch (Exception e) {
            throw new MMPException(e);
        }
    }
    return fileList;
}

From source file:com.ylife.goods.model.UploadImgUpyun.java

/**
 * //from ww  w.ja  v a  2s .c o m
 * 
 * @param item
 * @return ?
 */
public String uploadForRichEdit(FileItem item, UpyunConf upConf) {
    String resoult = null;
    if (item != null && item.getSize() != 0) {
        // ??java?
        @SuppressWarnings("unused")
        boolean flag = false;

        // ???????????
        String fileNamess = UploadImgCommon.getPicNamePathSuffix();

        File file = new File(fileNamess);
        try {
            item.write(file);
            if (upConf != null) {
                YunBean yb = new YunBean();
                yb.setBucketName(upConf.getBucketName());
                yb.setPassword(upConf.getPassWord());
                yb.setUserName(upConf.getUserName());
                UpYunUtil.yunUp(fileNamess, UploadImgCommon.prefix, yb, UploadImgCommon.suffix);
                // ??
                //LOGGER.debug(LOGGERINFO1 + upConf.getUrlPath() + UploadImgCommon.prefix + UploadImgCommon.suffix);
                resoult = upConf.getUrlPath() + UploadImgCommon.prefix + UploadImgCommon.suffix;
            } else {
                flag = true;
            }
        } catch (IllegalStateException e) {
            //LOGGER.error(LOGGERINFO4, e);
            flag = true;
        } catch (IOException e) {
            //LOGGER.error(LOGGERINFO4, e);
            flag = true;
        } catch (Exception e) {
            //LOGGER.error(LOGGERINFO4, e);
            flag = true;
        }
        return resoult;
    } else {
        return null;
    }
}

From source file:game.com.HandleUploadFileServlet.java

private void handle(HttpServletRequest request, AjaxResponseEntity responseObject) throws Exception {
    boolean isMultipart;
    String filePath;//from ww  w  .  j a  v a2 s .  c  o m
    int maxFileSize = 4 * 1024 * 1024;
    int maxMemSize = 4 * 1024 * 1024;
    File file;

    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);
    Map<String, List<FileItem>> postData = upload.parseParameterMap(request);
    if (postData.get("path") == null) {
        responseObject.returnCode = 0;
        responseObject.returnMessage = "invalid request";
        return;
    }
    String path = postData.get("path").get(0).getString();
    if (path == null) {
        responseObject.returnCode = 0;
        responseObject.returnMessage = "invalid request";
        return;
    }
    File folder = new File(path);
    if (!folder.exists()) {
        responseObject.returnCode = 0;
        responseObject.returnMessage = "path not exist";
        return;
    }
    if (folder.getAbsolutePath().startsWith(AppConfig.OPENSHIFT_DATA_DIR) == false) {
        responseObject.returnCode = 0;
        responseObject.returnMessage = "invalid path";
        return;
    }
    try {
        // Parse the request to get file items.
        List<FileItem> fileItems = postData.get("uploadfile");
        // Process the uploaded file items
        for (FileItem fi : fileItems) {
            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
                file = new File(path + "/" + fi.getName());
                fi.write(file);
                logger.info("upload " + file.getAbsolutePath());
            } else {
                logger.info("isFormField " + fi.getFieldName());
            }
        }

        responseObject.returnCode = 1;
        responseObject.returnMessage = "success";

    } catch (Exception ex) {
        logger.error(ex.getMessage(), ex);
    }
}

From source file:edu.temple.cis3238.wiki.ui.servlets.UploaderServlet.java

/**
 * Processes requests for HTTP  <code>POST</code> method.
 *
 * @param request  servlet request/*from   ww w  . j  a  va  2  s . c o  m*/
 * @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");
    try (PrintWriter out = response.getWriter()) {

        // checks if the request actually contains upload file
        if (!ServletFileUpload.isMultipartContent(request)) {
            // if not, we stop here
            PrintWriter writer = response.getWriter();
            writer.println("Error: Form must be  enctype = multipart/form-data.");
            writer.flush();
            setSuccess(false);
            return;
        }

        // configures upload settings
        DiskFileItemFactory factory = new DiskFileItemFactory();

        factory.setSizeThreshold(MEMORY_THRESHOLD);

        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setFileSizeMax(MAX_FILE_SIZE);
        upload.setSizeMax(MAX_REQUEST_SIZE);
        if (request.getSession() != null && request.getSession().getAttribute("topicCollection") != null) {
            try {
                collection = (TopicCollection) request.getSession().getAttribute("topicCollection");
                setTopic(collection.getCurrentTopic());
                setTopicID(getTopic().getTopicID() + "");
            } catch (Exception e) {
                e.printStackTrace();
                if (getTopic() == null) {
                    try {
                        setTopicID(request.getSession().getAttribute("topicID").toString());
                        setTopic(new TopicVOBuilder().setTopicID(Integer.parseInt(getTopicID())).build());
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            }
        } else {
            setTopicID("none");
        }

        String uploadPath = FileUtils.makeDir(getServletContext(), UPLOAD_DIRECTORY, getTopic());
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();

        }

        try {
            // parses the request's content to extract file data
            @SuppressWarnings("unchecked")
            List<FileItem> formItems = upload.parseRequest(request);
            String fileName = "";

            if (formItems != null && formItems.size() > 0) {
                // iterates over form's fields
                for (FileItem item : formItems) {

                    if (!item.isFormField()) {
                        fileName = new File(item.getName()).getName();
                        String filePath = uploadPath + File.separator + fileName;
                        System.out.println(filePath);
                        File storeFile = new File(filePath);

                        if (FileUtils.checkFileExtension(storeFile.getName().toLowerCase(), null)) {
                            item.write(storeFile);
                            request.setAttribute("sourceFile", fileName);
                            System.out.println("----------------------------");
                            System.out.println("FILENAME is :" + fileName);
                            System.out.println("----------------------------");
                            request.setAttribute("topicID", StringUtils.toS(getTopicID()));
                            setStatus(request, true, "Success: Topic " + StringUtils.toS(getTopicID())
                                    + " has saved file " + fileName + ". Upload has been done successfully!");
                        } else {
                            setStatus(request, false, "Exception: Invalid file extension");
                        }
                    }
                }
            } else {
                setStatus(request, false, "Exception: No valid file(s)");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            setStatus(request, false,
                    "Exception: " + StringUtils.coalesce(ex.getMessage(), ex.toString(), "unknown"));
        }
        // redirects client to message page
        getServletContext().getRequestDispatcher("/" + REDIRECT_ON_COMPLETE_PAGE).forward(request, response);
    }
}

From source file:com.manning.cmis.theblend.servlets.AddVersionServlet.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) {
        // show add version page
        dispatch("addversion.jsp", "Add new version. The Blend.", request, response);
    }/*from   ww  w.  ja  v a 2 s. c om*/

    Map<String, Object> properties = new HashMap<String, Object>();
    File uploadedFile = null;
    String docId = null;
    boolean major = true;
    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_DOC_ID.equalsIgnoreCase(name)) {
                    docId = item.getString();
                } else if (PARAM_MAJOR.equalsIgnoreCase(name)) {
                    major = Boolean.parseBoolean(item.getString());
                }
            } else {
                properties.put(PropertyIds.NAME, item.getName());

                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!", null);
    }

    try {
        // find the document
        Document doc = CMISHelper.getDocumet(session, docId, CMISHelper.LIGHT_OPERATION_CONTEXT, "document");

        // check out document and get Private Working Copy
        Document pwc = null;
        try {
            // check out
            ObjectId pwcId = doc.checkOut();

            // the PWC must be a document object
            pwc = (Document) session.getObject(pwcId, CMISHelper.LIGHT_OPERATION_CONTEXT);
        } catch (CmisBaseException cbe) {
            throw new TheBlendException("Checkout failed!", cbe);
        }

        // prepare the content stream
        ContentStream contentStream = null;
        try {
            contentStream = prepareContentStream(session, uploadedFile, doc.getType().getId(), properties);
        } catch (Exception e) {
            throw new TheBlendException("Upload failed: " + e, e);
        }

        // create new version
        try {
            newId = pwc.checkIn(major, properties, contentStream, null);
        } catch (CmisBaseException cbe) {
            throw new TheBlendException("Could not create new version: " + 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.ts.control.UploadFile.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    String campo1 = "";
    String campo2 = "";
    String campo3 = "";
    String campo4 = "";
    String campo5 = "";
    String campo6 = "";
    String campo7 = "";
    int c = 1;/*from  w ww. j av a  2 s. c o  m*/
    try {
        boolean ismultipart = ServletFileUpload.isMultipartContent(request);
        if (!ismultipart) {
        } else {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List items = null;
            try {
                items = upload.parseRequest(request);
            } catch (Exception e) {
            }
            Iterator itr = items.iterator();
            while (itr.hasNext()) {
                FileItem item = (FileItem) itr.next();
                if (item.isFormField()) {
                } else {
                    String itemname = item.getName();
                    if ((itemname == null || itemname.equals(""))) {
                        continue;
                    }
                    String filename = FilenameUtils.getName(itemname);
                    System.out.println("ruta---------------" + saveFile + filename);
                    File f = checkExist(filename);
                    item.write(f);
                    ////////
                    List cellDataList = new ArrayList();
                    try {
                        FileInputStream fileInputStream = new FileInputStream(f);
                        XSSFWorkbook workBook = new XSSFWorkbook(fileInputStream);
                        XSSFSheet hssfSheet = workBook.getSheetAt(0);
                        Iterator rowIterator = hssfSheet.rowIterator();
                        while (rowIterator.hasNext()) {
                            XSSFRow hssfRow = (XSSFRow) rowIterator.next();
                            Iterator iterator = hssfRow.cellIterator();
                            List cellTempList = new ArrayList();
                            while (iterator.hasNext()) {
                                XSSFCell hssfCell = (XSSFCell) iterator.next();
                                cellTempList.add(hssfCell);
                            }
                            cellDataList.add(cellTempList);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    out.println("<table border='3' class='table table-bordered table-striped table-hover'>");
                    for (int i = 1; i < cellDataList.size(); i++) {
                        List cellTempList = (List) cellDataList.get(i);
                        out.println("<tr>");
                        for (int j = 0; j < cellTempList.size(); j++) {
                            XSSFCell hssfCell = (XSSFCell) cellTempList.get(j);
                            String dato = hssfCell.toString();
                            out.print("<td>" + dato + "</td>");
                            switch (c) {
                            case 1:
                                campo1 = dato;
                                c++;
                                break;
                            case 2:
                                campo2 = dato;
                                c++;
                                break;
                            case 3:
                                campo3 = dato;
                                c++;
                                break;
                            case 4:
                                campo4 = dato;
                                c++;
                                break;
                            case 5:
                                campo5 = dato;
                                c++;
                                break;
                            case 6:
                                campo6 = dato;
                                c++;
                                break;
                            case 7:
                                campo7 = dato;
                                c = 1;
                                break;
                            }
                        }
                        //model.Consulta.addRegistros(campo1,campo2,campo3,campo4,campo5,campo6,campo7); 
                    }
                    out.println("</table><br>");
                    /////////
                }
            }
        }
    } catch (Exception e) {
    } finally {
        out.close();
    }
}

From source file:Controller.ControllerImageCustomerIndex.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from   w w w. j  a  v a 2  s  .  co  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 {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (!isMultipart) {

    } else {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List items = null;
        try {
            items = upload.parseRequest(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Iterator iter = items.iterator();
        Hashtable params = new Hashtable();
        String fileName = null;
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (item.isFormField()) {
                params.put(item.getFieldName(), item.getString());
            } else {

                try {
                    String itemName = item.getName();
                    fileName = itemName.substring(itemName.lastIndexOf("\\") + 1);
                    System.out.println("path" + fileName);
                    String RealPath = getServletContext().getRealPath("/") + "upload\\" + fileName;
                    System.out.println("Rpath" + RealPath);
                    File savedFile = new File(RealPath);
                    item.write(savedFile);
                    String username = (String) params.get("txtusername");
                    String password = (String) params.get("txpassword");
                    String hoten = (String) params.get("txthoten");
                    String gioitinh = (String) params.get("txtgioitinh");
                    String email = (String) params.get("txtemail");
                    String role = "false";
                    Customer cus = new Customer(username, password, hoten, gioitinh, email, role,
                            "upload\\" + fileName);

                    CustomerDAO.ThemKhachHang(cus);
                    RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
                    rd.forward(request, response);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }

    }

}

From source file:com.estampate.corteI.servlet.guardarEstampa.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/* ww  w .j a va  2  s .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 {
    String rutaImg = "NN";
    /*
     SUBIR LA IMAGEN AL SERVIDOR
     */
    dirUploadFiles = getServletContext().getRealPath(getServletContext().getInitParameter("dirUploadFiles"));
    if (ServletFileUpload.isMultipartContent(request)) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(new Long(getServletContext().getInitParameter("maxFileSize")).longValue());
        List listUploadFiles = null;
        FileItem item = null;
        try {
            listUploadFiles = upload.parseRequest(request);
            Iterator it = listUploadFiles.iterator();
            while (it.hasNext()) {
                item = (FileItem) it.next();
                if (!item.isFormField()) {
                    if (item.getSize() > 0) {
                        String nombre = item.getName();
                        String extension = nombre.substring(nombre.lastIndexOf("."));
                        File archivo = new File(dirUploadFiles, nombre);
                        item.write(archivo);
                        if (archivo.exists()) {
                            subioImagen = true;
                            rutaImg = "estampas/" + nombre;
                            //                response.sendRedirect("uploadsave.jsp");
                        } else {
                            subioImagen = false;
                        }
                    }
                } else {
                    campos.add(item.getString());
                }
            }
        } catch (FileUploadException e) {
            subioImagen = false;
        } catch (Exception e) {
            subioImagen = false;
        }
    }
    /*
     FIN DE SUBIR IMAGEN
     */
    String nombreImg = campos.get(1);
    EstampaCamiseta estampa = new EstampaCamiseta();
    //estampa.setIdEstampaCamiseta(null);
    //TRAIGO EL ARTISTA PARA GUARDARLO EN LA ESTAMPA
    datosGeneralesDAO artista = new datosGeneralesDAO();
    Artista artEstampa = artista.getArtista(Integer.parseInt(campos.get(0)));
    estampa.setArtista(artEstampa);
    //TRAIGO EL ARTISTA PARA GUARDARLO EN LA ESTAMPA
    datosGeneralesDAO rating = new datosGeneralesDAO();
    RatingEstampa ratingEstampa = rating.getRating(1);
    estampa.setRatingEstampa(ratingEstampa);
    //TRAIGO EL TAMAO QUE ELIGIERON DE LA ESTAMPA
    datosGeneralesDAO tamano = new datosGeneralesDAO();
    TamanoEstampa tamEstampa = tamano.getTamano(Integer.parseInt(campos.get(4)));
    estampa.setTamanoEstampa(tamEstampa);
    //TRAIGO EL TEMA QUE ELIGIERON DE LA ESTAMPA
    datosGeneralesDAO tema = new datosGeneralesDAO();
    TemaEstampa temaEstampa = tema.getTema(Integer.parseInt(campos.get(2)));
    estampa.setTemaEstampa(temaEstampa);
    //ASIGNO EL NOMBRE DE LA ESTAMPA
    estampa.setDescripcion(nombreImg);
    //ASIGNO LA RUTA DE LA IMAGEN QUE CREO
    estampa.setImagenes(rutaImg);
    //ASIGNO LA UBICACION DE LA IMAGEN EN LA CAMISA
    estampa.setUbicacion(campos.get(5));
    //ASIGNO EL PRECIO DE LA IMAGEN QUE CREO
    estampa.setPrecio(campos.get(3));
    //ASIGNO EL ID DEL LUGAR 
    estampa.setIdLugarEstampa(Integer.parseInt(campos.get(5)));
    guardarRegistroDAO guardarEstampa = new guardarRegistroDAO();
    guardarEstampa.guardaEstampa(estampa);
    processRequest(request, response);
}

From source file:Controller.ControllerImageCustomer.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*  ww w  . j  a  v  a  2s .  c  o  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (!isMultipart) {

    } else {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List items = null;
        try {
            items = upload.parseRequest(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Iterator iter = items.iterator();
        Hashtable params = new Hashtable();
        String fileName = null;
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (item.isFormField()) {
                params.put(item.getFieldName(), item.getString());
            } else {

                try {
                    String itemName = item.getName();
                    fileName = itemName.substring(itemName.lastIndexOf("\\") + 1);
                    System.out.println("path" + fileName);
                    String RealPath = getServletContext().getRealPath("/") + "upload\\" + fileName;
                    System.out.println("Rpath" + RealPath);
                    File savedFile = new File(RealPath);
                    item.write(savedFile);
                    String username = (String) params.get("txtusername");
                    String password = (String) params.get("txpassword");
                    String hoten = (String) params.get("txthoten");
                    String gioitinh = (String) params.get("txtgioitinh");
                    String email = (String) params.get("txtemail");
                    String role = "false";
                    String Register = (String) params.get("Register");
                    String url = "CustomerDao.jsp";
                    if (Register.equals("Register")) {
                        url = "index.jsp";
                    }
                    Customer cus = new Customer(username, password, hoten, gioitinh, email, role,
                            "upload\\" + fileName);
                    CustomerDAO.ThemKhachHang(cus);
                    RequestDispatcher rd = request.getRequestDispatcher(url);
                    rd.forward(request, response);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }

    }

}