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

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

Introduction

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

Prototype

String getName();

Source Link

Document

Returns the original filename in the client's filesystem, as provided by the browser (or other client software).

Usage

From source file:controladoresAdministrador.ControladorCargarInicial.java

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

    DiskFileItemFactory ff = new DiskFileItemFactory();

    ServletFileUpload sfu = new ServletFileUpload(ff);

    List items = null;
    File archivo = null;
    try {
        items = sfu.parseRequest(request);
    } catch (FileUploadException ex) {
        out.print(ex.getMessage());
    }
    String nombre = "";
    FileItem item = null;
    for (int i = 0; i < items.size(); i++) {

        item = (FileItem) items.get(i);

        if (!item.isFormField()) {
            nombre = item.getName();
            archivo = new File(this.getServletContext().getRealPath("/archivos/") + "/" + item.getName());
            try {
                item.write(archivo);
            } catch (Exception ex) {
                out.print(ex.getMessage());
            }
        }
    }
    CargaInicial carga = new CargaInicial();
    String ubicacion = archivo.toString();
    int cargado = carga.cargar(ubicacion);
    if (cargado == 1) {
        response.sendRedirect(
                "pages/indexadmin.jsp?msg=<strong><i class='glyphicon glyphicon-exclamation-sign'></i> No se encontro el archivo!</strong> Por favor intentelo de nuevo.&tipoAlert=warning");
    } else {
        response.sendRedirect(
                "pages/indexadmin.jsp?msg=<strong>Carga inicial exitosa! <i class='glyphicon glyphicon-ok'></i></strong>&tipoAlert=success");
    }
}

From source file:com.arcbees.bourseje.server.upload.Upload.java

@Override
public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles)
        throws UploadActionException {
    FileItem fileItem = sessionFiles.get(0);
    InputStream inputStream;/*from  ww w . ja  va2  s.co  m*/

    try {
        inputStream = fileItem.getInputStream();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    String servingUrl = imageUploadService.upload(fileItem.getName(), inputStream, fileItem.getSize());
    removeSessionFileItems(request);

    return servingUrl;
}

From source file:fr.aliasource.webmail.server.UploadAttachmentsImpl.java

@SuppressWarnings("rawtypes")
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    RequestContext ctx = new ServletRequestContext(req);
    String enc = ctx.getCharacterEncoding();
    logger.warn("received encoding is " + enc);
    if (enc == null) {
        enc = "utf-8";
    }//from  w ww .  j  av a2  s. c  o  m
    IAccount account = (IAccount) req.getSession().getAttribute("account");

    if (account == null) {
        resp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    DiskFileItemFactory factory = new DiskFileItemFactory(100 * 1024,
            new File(System.getProperty("java.io.tmpdir")));
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(20 * 1024 * 1024);

    List items = null;
    try {
        items = upload.parseRequest(req);
    } catch (FileUploadException e1) {
        logger.error("upload exception", e1);
        return;
    }

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

        if (!item.isFormField()) {
            id = item.getFieldName();
            String fileName = removePathElementsFromFilename(item.getName());
            logger.warn("FileItem: " + item);
            long size = item.getSize();
            logger.warn("pushing upload of " + fileName + " to backend for " + account.getLogin() + "@"
                    + account.getDomain() + " size: " + size + ").");
            AttachmentMetadata meta = new AttachmentMetadata();
            meta.setFileName(fileName);
            meta.setSize(size);
            meta.setMime(item.getContentType());
            try {
                account.uploadAttachement(id, meta, item.getInputStream());
            } catch (Exception e) {
                logger.error("Cannot write uploaded file to disk");
            }
        }
    }
}

From source file:com.uniquesoft.uidl.servlet.UploadServlet.java

/**
 * Delete an uploaded file.//w  w  w. j  a  v a2  s.c  o  m
 * 
 * @param request
 * @param response
 * @return FileItem
 * @throws IOException
 */
protected static FileItem removeUploadedFile(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    String parameter = request.getParameter(UConsts.PARAM_REMOVE);

    FileItem item = findFileItem(getSessionFileItems(request), parameter);
    if (item != null) {
        getSessionFileItems(request).remove(item);
        logger.debug("UPLOAD-SERVLET (" + request.getSession().getId() + ") removeUploadedFile: " + parameter
                + " " + item.getName() + " " + item.getSize());
    } else {
        logger.info("UPLOAD-SERVLET (" + request.getSession().getId() + ") removeUploadedFile: " + parameter
                + " not in session.");
    }

    renderXmlResponse(request, response, XML_DELETED_TRUE);
    return item;
}

From source file:com.gtwm.pb.model.manageData.fields.FileValueDefn.java

/**
 * Construct a file value reading the uploaded file name for a particlular
 * file field from the HTTP request//  w  w w.j  a  v a 2  s  .c o  m
 */
public FileValueDefn(HttpServletRequest request, FileField fileField, List<FileItem> multipartItems)
        throws CantDoThatException, FileUploadException, ObjectNotFoundException {
    if (!FileUpload.isMultipartContent(new ServletRequestContext(request))) {
        throw new CantDoThatException("To upload a file, the form must be posted as multi-part form data");
    }
    String internalFieldName = fileField.getInternalFieldName();
    ITEMLOOP: for (FileItem item : multipartItems) {
        // if item is a file
        if (!item.isFormField()) {
            if (item.getFieldName().equals(internalFieldName)) {
                this.filename = item.getName().replaceAll("^.*\\\\", "");
                break ITEMLOOP;
            }
        }
    }
    if (this.filename == null) {
        throw new ObjectNotFoundException("The file field " + fileField + "wasn't found in the user input");
    }
}

From source file:gabi.FileUploadServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  w w  w.  j a  v a2 s  .c  o m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    System.out.println("inside file upload");
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    if (isMultipart) {
        // Create a factory for disk-based file items  
        FileItemFactory factory = new DiskFileItemFactory();
        // Create a new file upload handler  
        ServletFileUpload upload = new ServletFileUpload(factory);
        boolean status = false;
        try {
            // Parse the request  
            List /* FileItem */ items = upload.parseRequest(request);
            Iterator iterator = items.iterator();
            while (iterator.hasNext()) {
                FileItem item = (FileItem) iterator.next();
                if (!item.isFormField()) {
                    String fileName = item.getName();
                    String root = getServletContext().getRealPath("/");
                    System.out.println("root path" + root);
                    File path = new File(root + "/uploads");
                    System.out.println("final path" + path);
                    if (!path.exists()) {
                        status = path.mkdirs();
                    }
                    File uploadedFile = new File(path + "/" + fileName);
                    System.out.println(uploadedFile.getAbsolutePath());
                    if (fileName != "") {
                        item.write(uploadedFile);
                        unzip(uploadedFile.getAbsolutePath(), root + "/uploads");
                        out.println("true");
                    } else {
                        System.out.println("File Uploaded Not Successful....");
                    }
                } else {
                    String abc = item.getString();
                    //        out.println("<br><br><h1>"+abc+"</h1><br><br>");  
                }
            }
        } catch (FileUploadException e) {
            System.out.println(e);
        }
    } else {
        out.println("false");
        System.out.println("Not Multipart");
    }
}

From source file:Controllers.EditItem.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from   w w  w.  j av a  2  s  . c om
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String id = null;
    String name = null;
    String itemCode = null;
    String price = null;
    String quantity = null;
    String category = null;
    String image = null;
    HttpSession session = request.getSession(true);
    User user = (User) session.getAttribute("user");
    if (user == null) {
        response.sendRedirect("login");
        return;
    }
    //        request.getServletContext().getRealPath("/uploads");
    String path = request.getServletContext().getRealPath("/uploads");
    System.out.println(path);

    if (ServletFileUpload.isMultipartContent(request)) {
        try {
            List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    String fileName = new File(item.getName()).getName();
                    //                        new File(path).mkdirs();
                    File directory = new File(path + File.separator + fileName);
                    image = fileName;
                    item.write(directory);
                } else {
                    if ("name".equals(item.getFieldName())) {
                        name = item.getString();
                    } else if ("id".equals(item.getFieldName())) {
                        id = item.getString();
                    } else if ("itemCode".equals(item.getFieldName())) {
                        itemCode = item.getString();
                    } else if ("price".equals(item.getFieldName())) {
                        price = item.getString();
                    } else if ("quantity".equals(item.getFieldName())) {
                        quantity = item.getString();
                    } else if ("category".equals(item.getFieldName())) {
                        category = item.getString();
                    }
                }
            }

            //File uploaded successfully
            System.out.println("done");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    boolean status = ItemRepository.editItem(name, itemCode, price, quantity, category, image, id);
    String message;
    System.out.println(status);
    if (status) {
        message = "Item saved successfully";
        response.sendRedirect("dashboard");
    } else {
        message = "Item not saved !!";
        request.setAttribute("message", message);
        request.getRequestDispatcher("dashboard/addItem.jsp").forward(request, response);
    }
}

From source file:com.Uploader.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new ServletException("Content type is not multipart/form-data");
    }//from  w  w  w.ja v  a 2  s .co m

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.write("<html><head></head><body>");
    try {
        List<FileItem> fileItemsList = uploader.parseRequest(request);
        Iterator<FileItem> fileItemsIterator = fileItemsList.iterator();
        while (fileItemsIterator.hasNext()) {
            FileItem fileItem = fileItemsIterator.next();
            System.out.println("FieldName=" + fileItem.getFieldName());
            System.out.println("FileName=" + fileItem.getName());
            System.out.println("ContentType=" + fileItem.getContentType());
            System.out.println("Size in bytes=" + fileItem.getSize());
            File file = new File(request.getServletContext().getAttribute("FILES_DIR") + File.separator
                    + fileItem.getName());
            System.out.println("Absolute Path at server=" + file.getAbsolutePath());
            fileItem.write(file);
            out.write("File " + fileItem.getName() + " uploaded successfully.");
            out.write("<br>");
            out.write("<a href=\"Uploader?fileName=" + fileItem.getName() + "\">Download " + fileItem.getName()
                    + "</a>");
        }
    } catch (FileUploadException e) {
        out.write("Exception in uploading file.");
        e.printStackTrace();
    } catch (Exception e) {
        out.write("Exception in uploading file.");
        e.printStackTrace();
    }
    out.write("</body></html>");
}

From source file:cpabe.controladores.UploadDownloadFileAdvancedServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new ServletException("Content type is not multipart/form-data");
    }//from   w w  w  . ja  v a 2  s  .c o m

    // response.setContentType("text/html");
    //  PrintWriter out = response.getWriter();
    // out.write("<html><head></head><body>");
    try {
        List<FileItem> fileItemsList = uploader.parseRequest(request);
        Iterator<FileItem> fileItemsIterator = fileItemsList.iterator();
        while (fileItemsIterator.hasNext()) {
            FileItem fileItem = fileItemsIterator.next();

            System.out.println("FieldName=" + fileItem.getFieldName());
            System.out.println("FileName=" + fileItem.getName());
            System.out.println("ContentType=" + fileItem.getContentType());
            System.out.println("Size in bytes=" + fileItem.getSize());

            File file = new File(request.getServletContext().getAttribute("FILES_DIR") + File.separator
                    + fileItem.getName());
            //setar no objeto CaminhoArquivo os dados do arquivo anexado
            String caminho = file.getAbsolutePath();
            String nome = fileItem.getName();

            CaminhoArquivo c = new CaminhoArquivo();
            c.setNome(nome);
            c.setWay(caminho);

            request.setAttribute("caminho", c);
            System.out.println("caminho=" + caminho);
            System.out.println("nome=" + nome);

            System.out.println("Absolute Path at server=" + file.getAbsolutePath());
            fileItem.write(file);

            request.getRequestDispatcher("/avancado/encriptar/encriptar1.jsp").forward(request, response);

            // out.write("File " + fileItem.getName() + " uploaded successfully.");
            // out.write("<br>");
            // out.write("<a href=\"UploadDownloadFileServlet?fileName=" + fileItem.getName() + "\">Download " + fileItem.getName() + "</a>");
        }

    } catch (FileUploadException e) {
        //  out.write("Exception in uploading file.");
    } catch (Exception e) {
        //  out.write("Exception in uploading file.");
    }
    // out.write("</body></html>");
}

From source file:cpabe.controladores.UploadDownloadFileServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new ServletException("Content type is not multipart/form-data");
    }/* w  ww  .  j  a va 2  s .c o m*/

    // response.setContentType("text/html");
    //  PrintWriter out = response.getWriter();
    // out.write("<html><head></head><body>");
    try {
        List<FileItem> fileItemsList = uploader.parseRequest(request);
        Iterator<FileItem> fileItemsIterator = fileItemsList.iterator();
        while (fileItemsIterator.hasNext()) {
            FileItem fileItem = fileItemsIterator.next();

            System.out.println("FieldName=" + fileItem.getFieldName());
            System.out.println("FileName=" + fileItem.getName());
            System.out.println("ContentType=" + fileItem.getContentType());
            System.out.println("Size in bytes=" + fileItem.getSize());

            File file = new File(request.getServletContext().getAttribute("FILES_DIR") + File.separator
                    + fileItem.getName());
            //setar no objeto CaminhoArquivo os dados do arquivo anexado
            String caminho = file.getAbsolutePath();
            String nome = fileItem.getName();

            CaminhoArquivo c = new CaminhoArquivo();
            c.setNome(nome);
            c.setWay(caminho);

            request.setAttribute("caminho", c);
            System.out.println("caminho=" + caminho);
            System.out.println("nome=" + nome);

            System.out.println("Absolute Path at server=" + file.getAbsolutePath());
            fileItem.write(file);

            request.getRequestDispatcher("/formularios/encriptar/encriptar1.jsp").forward(request, response);

            // out.write("File " + fileItem.getName() + " uploaded successfully.");
            // out.write("<br>");
            // out.write("<a href=\"UploadDownloadFileServlet?fileName=" + fileItem.getName() + "\">Download " + fileItem.getName() + "</a>");
        }

    } catch (FileUploadException e) {
        //  out.write("Exception in uploading file.");
    } catch (Exception e) {
        //  out.write("Exception in uploading file.");
    }
    // out.write("</body></html>");
}