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:forseti.JSubirArchivo.java

@SuppressWarnings("rawtypes")
public int processFiles(Vector archivos) {
    int numFiles = 0, thisFile = 0;

    try {/*from w w w .  ja  v a 2  s  . c o  m*/
        FileItem actual = null;

        for (int i = 0; i < archivos.size(); i++) {
            actual = (FileItem) archivos.elementAt(i);
            String fileName = actual.getName();
            // construimos un objeto file para recuperar el trayecto completo
            File file = new File(fileName);
            String ext = "." + getExt(thisFile).toLowerCase();
            boolean frz = isFrz(thisFile);
            //System.out.println("Archivo: " + fileName + " Ext esperada: " + ext);

            // Verifica que el archivo sea de la extension esperada
            if (file.getName().toLowerCase().indexOf(ext) != -1) {
                // nos quedamos solo con el nombre y descartamos el path
                file = new File(m_Path + file.getName());
                // escribimos el fichero colgando del nuevo path
                actual.write(file);
                MyUploadedFiles part = (MyUploadedFiles) m_Files.elementAt(thisFile);
                part.m_File = file.getName();

                numFiles += 1;
            } else if (frz) //Si era forzozo 
                m_Error += " " + JUtil.Msj("GLB", "GLB", "GLB", "ARCHIVO", 4) + " " + file.getName() + " - "
                        + ext;

            thisFile += 1;

        }

    } catch (Exception e) {
        if (e != null)
            m_Error += " " + JUtil.Msj("GLB", "GLB", "GLB", "ARCHIVO", 3) + " " + e.getMessage(); //"Error al subir archivos: " + e.getMessage();
    }

    return numFiles;
}

From source file:com.krawler.workflow.module.dao.BaseBuilderDao.java

public void uploadFile(FileItem fi, String destinationDirectory, String fileName) throws ServiceException {
    try {/*from  ww w .j  a v  a  2 s.  c  o  m*/
        File destDir = new File(destinationDirectory);
        if (!destDir.exists()) {
            destDir.mkdirs();
        }
        File uploadFile = new File(destinationDirectory, fileName);
        fi.write(uploadFile);
    } catch (Exception ex) {
        logger.warn(ex.getMessage(), ex);
        throw ServiceException.FAILURE("moduleBuilderMethods.uploadFile", ex);
    }

}

From source file:com.silverpeas.gallery.servlets.GalleryDragAndDrop.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    SilverTrace.info("gallery", "GalleryDragAndDrop.doPost", "root.MSG_GEN_ENTER_METHOD");
    String userId = null;//from   ww  w. j a  va 2 s. c o  m
    HttpRequest request = HttpRequest.decorate(req);
    try {
        request.setCharacterEncoding("UTF-8");
        String componentId = request.getParameter("ComponentId");
        String albumId = request.getParameter("AlbumId");
        userId = request.getParameter("UserId");
        SilverTrace.info("gallery", "GalleryDragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE",
                "componentId = " + componentId + " albumId = " + albumId + " userId = " + userId);
        String savePath = FileRepositoryManager.getTemporaryPath() + File.separatorChar + userId
                + System.currentTimeMillis() + File.separatorChar;
        List<FileItem> items = request.getFileItems();
        String parentPath = getParameterValue(items, "userfile_parent");
        SilverTrace.info("gallery", "GalleryDragAndDrop.doPost.doPost", "root.MSG_GEN_PARAM_VALUE",
                "parentPath = " + parentPath);

        SilverTrace.info("gallery", "GalleryDragAndDrop.doPost.doPost", "root.MSG_GEN_PARAM_VALUE",
                "debut de la boucle");
        for (FileItem item : items) {
            if (!item.isFormField()) {
                String fileName = FileUploadUtil.getFileName(item);
                SilverTrace.info("gallery", "GalleryDragAndDrop.doPost.doPost", "root.MSG_GEN_PARAM_VALUE",
                        "item = " + item.getFieldName() + " - " + fileName);
                if (fileName != null) {
                    SilverTrace.info("gallery", "GalleryDragAndDrop.doPost.doPost", "root.MSG_GEN_PARAM_VALUE",
                            "fileName = " + fileName);
                    // modifier le nom avant de l'crire
                    File f = new File(savePath + File.separatorChar + fileName);
                    File parent = f.getParentFile();
                    if (!parent.exists()) {
                        parent.mkdirs();
                    }
                    item.write(f);
                    // Cas du zip
                    if (FileUtil.isArchive(fileName)) {
                        ZipManager.extract(f, parent);
                    }
                }
            }
        }
        importRepository(new File(savePath), userId, componentId, albumId);
        FileFolderManager.deleteFolder(savePath);
    } catch (Exception e) {
        SilverTrace.debug("gallery", "GalleryDragAndDrop.doPost.doPost", "root.MSG_GEN_PARAM_VALUE", e);
        final StringBuilder sb = new StringBuilder("ERROR");
        final String errorMessage = SilverpeasTransverseWebErrorUtil.performAppletAlertExceptionMessage(e,
                UserDetail.getById(userId).getUserPreferences().getLanguage());
        if (isDefined(errorMessage)) {
            sb.append(": ");
            sb.append(errorMessage);
        }
        res.getOutputStream().println(sb.toString());
    }
    res.getOutputStream().println("SUCCESS");
}

From source file:hu.sztaki.lpds.pgportal.portlets.credential.AssertionPortlet.java

/**
 * Checks if the SAML file exists in the user's directory. Proper messages
 * are sent to the GUI.//from w w w  .j  a  v  a 2 s.  c o  m
 * @param session PortletSession a portlet session object
 * @param samlfile FileItem the SAML Asertion
 * @param usrId String containing the user id
 * @throws Exception
 */
private synchronized List<String> uploadSaml(PortletSession session, FileItem samlfile, String sresource,
        String usrId) throws Exception {
    logger.debug("samlfile:" + samlfile.getName() + " sresource:" + sresource);
    FileItem sf = samlfile;
    String userId = usrId;
    String retval = null;

    UUID uuid = UUID.randomUUID();
    String tmpName = loadUsersDirPath(userId);
    File saveTotmp = File.createTempFile("tmp", "x509up", new File(tmpName));
    List<String> result = new Vector<String>();

    try {
        checkFile("SAML", samlfile);
        sf.write(saveTotmp);
        HashMap samldetails = getSAMLDetail(saveTotmp); // check, if it is a valid assertion, or not

        List<String> resources = getResources(session, sresource, (String) samldetails.get("subject"));

        for (String sres : resources) {
            try {
                String sdestfile = tmpName + "/" + "x509up." + sres;

                File destfile = new File(sdestfile);

                if (destfile.exists()) {
                    destfile.delete();
                }

                sf.write(destfile);
                result.add("Upload successful for resource: " + sres);
            } catch (Exception e) {
                result.add("Upload for " + sres + " failed. Reason: " + e.getMessage());
                logger.warn("Upload for " + sres + " failed. Reason: " + e.getMessage());
                logger.debug("Exception: ", e);
            }
        }

    } catch (Exception e) {
        if (saveTotmp.exists()) {
            saveTotmp.delete();
        }
        throw e;
    }
    if (saveTotmp.exists()) {
        saveTotmp.delete();
    }
    return result;
}

From source file:controller.controller.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   ww w. j av  a2 s  . com*/
 *
 * @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");
    HttpSession session = request.getSession();
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */
        String action = request.getParameter("action");
        String type = request.getParameter("type");
        System.out.println(action);
        if (action.equals("getproduct")) {
            System.out.println(type);
            DAO dao = new DAO();
            ArrayList<pro> product = dao.getProduct(type);
            session.setAttribute("product", product);
            dispatcher(request, response, "tablet.jsp");
        }

        if (action.equals("productDetail")) {
            int id = Integer.parseInt(request.getParameter("id"));
            DAO detail = new DAO();
            pro productDetail = detail.productDetail(id);
            session.setAttribute("productdetail", productDetail);
            dispatcher(request, response, "view.jsp");
        }
        if (action.equals("AddtoCart")) {
            System.out.println(action);
            shoppingCart cart = (shoppingCart) session.getAttribute("cart");

            if (cart == null) {
                System.out.println("cart: " + null);
                cart = new shoppingCart();
            }

            System.out.println("product " + session.getAttribute("productdetail"));

            pro temp = (pro) session.getAttribute("productdetail");
            int qu = temp.getQuantity();
            System.out.println("qu " + qu);
            if (qu > 0) {
                --qu;
                System.out.println("qu " + qu);
                temp.setQuantity(qu);
                //int quantity = Integer.parseInt(request.getParameter("quantity"));

                cart.addProduct(temp);
                System.out.println("cart " + cart.getProducts().size());
            }
            session.setAttribute("cart", cart);

        }
        if (action.equals("checkout")) {
            System.out.println(action);
            shoppingCart cart = (shoppingCart) session.getAttribute("cart");
            if (cart == null) {
                cart = new shoppingCart();
            }
            session.setAttribute("cart", cart);
            dispatcher(request, response, "checkout.jsp");
        }

        if (action.equals("order")) {
            shoppingCart cart = (shoppingCart) session.getAttribute("cart");
            String accid = (String) session.getAttribute("login");
            DAO dao = new DAO();
            dao.order(cart, accid);
            session.removeAttribute("cart");
            response.sendRedirect("index.jsp");

        }
        if (action.equals("upload")) {

            String dirNames = "D:\\Task\\IU\\Web Application Development\\New\\Final project\\ECommerceProject";

            String user = (String) session.getAttribute("login");

            String fileName = null;
            boolean isMultiPArt = ServletFileUpload.isMultipartContent(request);

            if (isMultiPArt) {
                System.out.println(1);
                FileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                List items = null;
                try {
                    items = upload.parseRequest(request);
                } catch (FileUploadException e) {
                    e.printStackTrace();
                }
                Iterator iter = items.iterator();
                Hashtable params = new Hashtable();

                File theDir = new File(dirNames + File.separator + user);

                // if the directory does not exist, create it
                if (!theDir.exists()) {
                    System.out.println("creating directory: " + user);
                    boolean result = false;

                    try {
                        theDir.mkdir();
                        result = true;
                    } catch (SecurityException se) {
                        //handle it
                    }
                    if (result) {
                        System.out.println("DIR created");
                    }
                }
                String[] url = new String[5];
                int cnt = 0;
                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 = dirNames + File.separator + user + File.separator + fileName;
                            System.out.println("realPath: " + realPath);
                            File savedFile = new File(realPath);
                            item.write(savedFile);
                            url[cnt] = "./database" + File.separator + user + File.separator + fileName;
                            ++cnt;
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }

                String name = (String) params.get("name");
                String price = (String) params.get("price");
                String quantity = (String) params.get("quantity");
                String typepr = (String) params.get("type");

                System.out.println(name + " " + price + " " + quantity + " " + typepr);

                DAO uploadReal = new DAO();
                uploadReal.inserPro(name, price, quantity, typepr, url[0]);
                //                        newUser = new User();
                //                        newUser.setEmail(Email);
                out.print(url[0]);
                String temp = ".\\User" + File.separator + user + File.separator + fileName;
                System.out.println("Temp " + temp);

                //Connector.editUser(myProfile.getEmail(), newUser);
                //response.sendRedirect("index.jsp");
                dispatcher(request, response, "index.jsp");
            }

        }
    }

}

From source file:edu.xtec.colex.client.beans.ColexIndexBean.java

/**
 * Calls the web service operation <I>importCollection(User,Collection,FILE)
 * : void</I>/*w ww  .j  a  va  2 s .  c o  m*/
 *
 * @param importName the String name of the Collection to import
 * @param fiImport the FileItem Zip of the Collection to import
 * @throws java.lang.Exception when an Exception error occurs
 */
private void importCollection(String importName, FileItem fiImport) throws Exception {
    User uRequest = new User(getUserId());
    Collection cRequest = new Collection(importName);
    File fTemp = null;

    try {
        smRequest = mf.createMessage();

        SOAPBody sbRequest = smRequest.getSOAPBody();

        Name n = sf.createName("importCollection");

        SOAPBodyElement sbeRequest = sbRequest.addBodyElement(n);

        sbeRequest.addChildElement(uRequest.toXml());
        sbeRequest.addChildElement(cRequest.toXml());

        String sNomFitxer = Utils.getFileName(fiImport.getName());

        fTemp = File.createTempFile("attach", null);

        fiImport.write(fTemp);

        URL urlFile = new URL("file://" + fTemp.getPath());

        AttachmentPart ap = smRequest.createAttachmentPart(new DataHandler(urlFile));

        smRequest.addAttachmentPart(ap);

        smRequest.saveChanges();

        SOAPMessage smResponse = sendMessage(smRequest,
                this.getJspProperties().getProperty("url.servlet.collection"));

        SOAPBody sbResponse = smResponse.getSOAPBody();

        if (sbResponse.hasFault()) {
            checkFault(sbResponse, "import");
        } else {

        }

    } catch (Exception e) {
        throw e;
    } finally {
        if (fTemp != null) {
            fTemp.delete();
        }
    }
}

From source file:Admin.products.ProductS.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./* w w 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");
    try (PrintWriter out = response.getWriter()) {

        String brand = request.getParameter("sel01n");
        String category_1 = request.getParameter("sel02n");
        String category_2 = request.getParameter("sel03n");
        String category_3 = request.getParameter("sel04n");
        String product_name = request.getParameter("txf01n");
        String description = request.getParameter("txa01n");
        String specifications = request.getParameter("spe00n");

        try {

            String Name = null;
            String Price = null;
            String QTY = null;

            FileItemFactory item = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(item);

            List<FileItem> list = upload.parseRequest(request);

            for (FileItem fileItem : list) {

                if (fileItem.isFormField()) { //form field

                    //                        fileItem.getFieldName().equals("sel01n")) {
                    Name = fileItem.getString();

                    if (fileItem.getFieldName().equals("spe01n")) {
                        System.out.println("NAME-----:" + Name);
                    } else if (fileItem.getFieldName().equals("spe02n")) {
                        System.out.println("VALUE-----:" + Name);
                    }

                } else {

                    System.out.println("---------------" + fileItem.getName());

                    //                        String n = new File(fileItem.getName()).getName();
                    System.out.println(request.getServletContext().getRealPath("/04_admin/product/img/") + "\\"
                            + System.currentTimeMillis() + ".jpg");
                    fileItem.write(new File(request.getServletContext().getRealPath("/04_admin/product/img/")
                            + "\\" + System.currentTimeMillis() + ".jpg"));
                }
            }

        } catch (Exception e) {
            throw new ServletException(e);
        }
    }
}

From source file:com.intranet.intr.PosControler.java

@RequestMapping(value = "fotoPostulante.htm", method = RequestMethod.POST)
public String fotoEmpleado_post(@ModelAttribute("postulante") postulantes postulante, BindingResult result,
        HttpServletRequest request, Principal principal) {
    String mensaje = "";
    String ubicacionArchivo = "C:\\glassfish-4.1.1-web\\glassfish4\\glassfish\\domains\\domain1\\applications\\Intranet\\resources\\fotosPerfil";
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(1024);//from   ww  w. java  2  s . c  o  m

    ServletFileUpload upload = new ServletFileUpload(factory);
    String name = principal.getName();
    postulantes po = new postulantes();

    try {
        List<FileItem> partes = upload.parseRequest(request);
        for (FileItem item : partes) {
            System.out.println("NOMBRE FOTO: " + item.getName());
            File file = new File(ubicacionArchivo, item.getName());
            item.write(file);
            users u = usuarioService.getByLogin(name);
            po = postulanteService.ByNif(u.getNif());
            po.setNombrefotografia(item.getName());
            postulanteService.UpdateImagen(po);
        }
        System.out.println("Archi subido correctamente");
    } catch (Exception ex) {
        System.out.println("Error al subir archivo" + ex.getMessage());
    }

    //return "redirect:uploadFile.htm";

    return "redirect:ActualizarfotoPostulante.htm";

}

From source file:it.infn.ct.mpi_portlet.java

void processInputFile(FileItem item) {
    String fileName = item.getName();
    if (!fileName.equals("")) {
        String fieldName = item.getFieldName();
        String theNewFileName = "/tmp/" + fileName;
        File uploadedFile = new File(theNewFileName);
        _log.info("Uploading file: '" + fileName + "' into '" + theNewFileName + "'");
        try {//  ww w  . j  av a  2 s  . c  o m
            item.write(uploadedFile);
        } catch (Exception e) {
            _log.info("Caught exception while uploading file: 'file_inputFile'");
        }
        // File content has to be inserted into String variables:
        //   inputFileName -> inputFileText
        try {
            if (fieldName.equals("file_inputFile"))
                inputFileText = updateString(theNewFileName);
            // Other params can be added as below ...
            //else if(fieldName.equals("..."))
            //   ...=updateString(theNewFileName);
            else { // Never happens
            }
        } catch (Exception e) {
            _log.info("Caught exception while processing strings: '" + e.toString() + "'");
        }
    }
}

From source file:forseti.JSubirArchivo.java

@SuppressWarnings("rawtypes")
public int processFiles(HttpServletRequest request, boolean onlyOne) // Request No debe contener parametros de formulario, sino solo los parmetro del archivo
{
    int numFiles = 0, thisFile = 0;

    try {/* ww w  .ja v  a  2  s .com*/
        // construimos el objeto que es capaz de parsear la pericin
        DiskFileUpload fu = new DiskFileUpload();
        // maximo numero de bytes
        fu.setSizeMax(1024 * m_MaxSize); // 512 K
        // tamao por encima del cual los ficheros son escritos directamente en disco
        fu.setSizeThreshold(4096);
        // directorio en el que se escribirn los ficheros con tamao superior al soportado en memoria
        fu.setRepositoryPath("/tmp");
        // ordenamos procesar los ficheros
        List fileItems = fu.parseRequest(request);
        if (fileItems == null) {
            m_Error += JUtil.Msj("GLB", "GLB", "GLB", "ARCHIVO", 3) + " null";
            return 0;
        }
        // Iteramos por cada fichero
        Iterator i = fileItems.iterator();
        FileItem actual = null;

        if (onlyOne) {
            actual = (FileItem) i.next();
            String fileName = actual.getName();
            // construimos un objeto file para recuperar el trayecto completo
            File file = new File(fileName);

            // Verifica que el archivo sea de la extension esperada
            for (int f = 0; f < m_Files.size(); f++) {
                String ext = "." + getExt(f).toLowerCase();
                System.out.println("Archivo: " + fileName + " Ext esperada: " + ext);

                if (file.getName().toLowerCase().indexOf(ext) != -1) {
                    // nos quedamos solo con el nombre y descartamos el path
                    file = new File(m_Path + file.getName());
                    // escribimos el fichero colgando del nuevo path
                    actual.write(file);
                    MyUploadedFiles part = (MyUploadedFiles) m_Files.elementAt(thisFile);
                    part.m_File = file.getName();

                    numFiles += 1;
                    break;
                }
            }

            if (numFiles == 0)
                m_Error += " " + JUtil.Msj("GLB", "GLB", "GLB", "ARCHIVO", 4) + " " + file.getName();

        } else {
            while ((actual = (FileItem) i.next()) != null) {
                String fileName = actual.getName();
                // construimos un objeto file para recuperar el trayecto completo
                File file = new File(fileName);
                String ext = "." + getExt(thisFile).toLowerCase();
                System.out.println("Archivo: " + fileName + " Ext esperada: " + ext);

                // Verifica que el archivo sea de la extension esperada
                if (file.getName().toLowerCase().indexOf(ext) != -1) {
                    // nos quedamos solo con el nombre y descartamos el path
                    file = new File(m_Path + file.getName());
                    // escribimos el fichero colgando del nuevo path
                    actual.write(file);
                    MyUploadedFiles part = (MyUploadedFiles) m_Files.elementAt(thisFile);
                    part.m_File = file.getName();

                    numFiles += 1;
                } else
                    m_Error += " " + JUtil.Msj("GLB", "GLB", "GLB", "ARCHIVO", 4) + " " + file.getName() + " - "
                            + ext;

                thisFile += 1;
            }
            System.out.println("Despues while");
        }
    } catch (Exception e) {
        if (e != null)
            m_Error += " " + JUtil.Msj("GLB", "GLB", "GLB", "ARCHIVO", 3) + " " + e.getMessage(); //"Error al subir archivos: " + e.getMessage();
    }

    return numFiles;
}