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:net.daw.control.upload.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.// www . j av 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("application/json;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        String name = "";
        String strMessage = "";
        HashMap<String, String> hash = new HashMap<>();
        if (ServletFileUpload.isMultipartContent(request)) {
            try {
                List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory())
                        .parseRequest(request);
                for (FileItem item : multiparts) {
                    if (!item.isFormField()) {
                        name = new File(item.getName()).getName();
                        item.write(new File(".//..//webapps//images//" + name));
                    } else {
                        hash.put(item.getFieldName(), item.getString());
                    }
                }
                Gson oGson = new Gson();
                Map<String, String> data = new HashMap<>();
                Iterator it = hash.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry e = (Map.Entry) it.next();
                    data.put(e.getKey().toString(), e.getValue().toString());
                }
                data.put("imglink", "http://" + request.getServerName() + ":" + request.getServerPort()
                        + "/images/" + name);
                out.print("{\"status\":200,\"message\":" + oGson.toJson(data) + "}");
            } catch (Exception ex) {
                strMessage += "File Upload Failed: " + ex;
                out.print("{\"status\":500,\"message\":\"" + strMessage + "\"}");
            }
        } else {
            strMessage += "Only serve file upload requests";
            out.print("{\"status\":500,\"message\":\"" + strMessage + "\"}");
        }
    }
}

From source file:com.eufar.asmm.server.UploadImage.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    System.out.println("UploadImage - the function started");
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(MAX_MEMORY_SIZE);
    String uploadFolder = getServletContext().getRealPath("") + DATA_DIRECTORY;
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(MAX_REQUEST_SIZE);
    double maxSize = (MAX_REQUEST_SIZE / 1024) / 1024;
    System.out.println("UploadImage - max image size: " + maxSize + " Mbytes");
    try {//  www.  ja v a2s  . c  o  m
        @SuppressWarnings("rawtypes")
        List items = upload.parseRequest(request);
        @SuppressWarnings("rawtypes")
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            Object obj = iter.next();
            org.apache.commons.fileupload.FileItem item = (org.apache.commons.fileupload.FileItem) obj;
            String fileExt = FilenameUtils.getExtension(item.getName());
            if (fileExt.matches("(jpg|jpeg|bmp|png|JPG|JPEG|BMP|PNG)")) {
                System.out.println("UploadImage - image accepted");
                if (!item.isFormField()) {
                    File uploadedFile = File.createTempFile("tmp_", "." + fileExt, new File(uploadFolder));
                    item.write(uploadedFile);
                    double fileSize = item.getSize();
                    fileSize = (fileSize / 1024) / 1024;
                    response.setCharacterEncoding("UTF-8");
                    response.setContentType("text/html");
                    response.getWriter().write(uploadedFile.getName());
                    System.out.println("UploadImage - " + uploadedFile.getPath() + ": upload ok...");
                    System.out.println("UploadImage - " + uploadedFile.getPath() + ": " + fileSize + " MBytes");
                    if (new File(uploadedFile.getPath()).isFile()) {
                        System.out.println("PrintFunction - picture (webapps): the file exists.");
                    } else {
                        System.out.println("PrintFunction - picture (webapps): the file doesn't exist.");
                    }
                    if (new File(uploadedFile.getPath()).isFile()) {
                        System.out.println("PrintFunction - picture (webapps): the file can be read.");
                    } else {
                        System.out.println("PrintFunction - picture (webapps): the file can't be read.");
                    }
                } else {
                    System.out.println("UploadImage - a problem occured with the file format");
                }
            } else {
                System.out.println("UploadImage - image rejected: wrong format");
                response.setCharacterEncoding("UTF-8");
                response.setContentType("text/html");
                response.getWriter().write("format");
            }
        }
    } catch (Exception ex) {
        System.out.println("UploadImage - a problem occured: " + ex);
        response.getWriter().write("ERROR:" + ex.getMessage());
    }
}

From source file:com.ephesoft.gxt.admin.server.ImportTableUploadServlet.java

/**
 * This API is used to get table file name.
 * //from w ww.ja va 2  s  . c  om
 * @param item {@link FileItem} uploaded file item.
 * @return {@link String} table file name.
 */
private String getTableFileName(final FileItem item) {
    String tableFileName = item.getName();
    if (tableFileName != null) {
        tableFileName = tableFileName.substring(tableFileName.lastIndexOf(File.separator) + 1);
        tableFileName = FilenameUtils.getName(tableFileName);
    }
    return tableFileName;
}

From source file:info.magnolia.cms.filters.CommonsFileUploadMultipartRequestFilter.java

/**
 * Add the <code>FileItem</code> as a document into the <code>MultipartForm</code>.
 *///from   w w w.j  a  v a 2s  . c  o m
private void addFile(FileItem item, MultipartForm form) throws Exception {
    String atomName = item.getFieldName();
    String fileName = item.getName();
    String type = item.getContentType();
    File file = File.createTempFile(atomName, null, this.tempDir);
    item.write(file);

    form.addDocument(atomName, fileName, type, file);
}

From source file:br.com.caelum.vraptor.observer.upload.CommonsUploadMultipartObserver.java

protected void processFile(FileItem item, String name, MutableRequest request) {
    try {//from w  w  w  .j a v a2 s.c om
        String fileName = FilenameUtils.getName(item.getName());
        UploadedFile upload = new DefaultUploadedFile(item.getInputStream(), fileName, item.getContentType(),
                item.getSize());
        request.setParameter(name, name);
        request.setAttribute(name, upload);

        logger.debug("Uploaded file: {} with {}", name, upload);
    } catch (IOException e) {
        throw new InvalidParameterException("Cant parse uploaded file " + item.getName(), e);
    }
}

From source file:controllers.ControladorFotoCoin.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from  w  w w  .j a  v a  2 s.com*/
 * @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 {
    int idMatch = Integer.parseInt(request.getParameter("idMatch"));
    String userPath = "";
    String UPLOAD_DIRECTORY = "/Users/patriciacuevas/NetBeansProjects/PerfectMatchTis2/web/fotosUsuarios";
    if (ServletFileUpload.isMultipartContent(request)) {
        String pathFile = "";
        try {
            List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    String name = new File(item.getName()).getName();
                    pathFile = UPLOAD_DIRECTORY + File.separator + name;
                    item.write(new File(pathFile));

                }
            }

            PmtMatchDTO match = new PmtMatchDTO();
            match.setMatId(idMatch);

            PmtIntercambioFotosDTO intercambio = new PmtIntercambioFotosDTO();
            intercambio.setInfRutaUsuarioCoincidente(pathFile);
            intercambio.setMat(match);

            intercambio.guardar(intercambio);

            request.setAttribute("message", "Su foto fue enviada exitosamente");
            userPath = "cliente";

        } catch (Exception ex) {
            request.setAttribute("message", "Error al cargar el archivo");
            userPath = "enviarFotoCoincidente";
        }

        String url = "WEB-INF/view/" + userPath + ".jspf";
        RequestDispatcher rd = request.getRequestDispatcher(url);
        rd.forward(request, response);
    }
}

From source file:hoot.services.ingest.MultipartSerializer.java

protected void _serializeFGDB(List<FileItem> fileItemsList, String jobId, Map<String, String> uploadedFiles,
        Map<String, String> uploadedFilesPaths) throws Exception {
    Iterator<FileItem> fileItemsIterator = fileItemsList.iterator();
    Map<String, String> folderMap = new HashMap<String, String>();

    while (fileItemsIterator.hasNext()) {
        FileItem fileItem = fileItemsIterator.next();
        String fileName = fileItem.getName();

        String relPath = FilenameUtils.getPath(fileName);
        if (relPath.endsWith("/")) {
            relPath = relPath.substring(0, relPath.length() - 1);
        }// w  w w .j a v  a2  s  . com
        fileName = FilenameUtils.getName(fileName);

        String fgdbFolderPath = homeFolder + "/upload/" + jobId + "/" + relPath;

        String pathVal = folderMap.get(fgdbFolderPath);
        if (pathVal == null) {
            File folderPath = new File(fgdbFolderPath);
            FileUtils.forceMkdir(folderPath);
            folderMap.put(fgdbFolderPath, relPath);
        }

        if (fileName == null) {
            ResourceErrorHandler.handleError("A valid file name was not specified.", Status.BAD_REQUEST, log);
        }

        String uploadedPath = fgdbFolderPath + "/" + fileName;
        File file = new File(uploadedPath);
        fileItem.write(file);
    }

    Iterator it = folderMap.entrySet().iterator();
    while (it.hasNext()) {
        String nameOnly = "";
        Map.Entry pairs = (Map.Entry) it.next();
        String fgdbName = pairs.getValue().toString();
        String[] nParts = fgdbName.split("\\.");

        for (int i = 0; i < nParts.length - 1; i++) {
            if (nameOnly.length() > 0) {
                nameOnly += ".";
            }
            nameOnly += nParts[i];
        }
        uploadedFiles.put(nameOnly, "GDB");
        uploadedFilesPaths.put(nameOnly, fgdbName);
    }
}

From source file:edu.gmu.csiss.automation.pacs.servlet.FileUploadServlet.java

private void processUploadFile(FileItem item, PrintWriter pw) throws Exception {
    String filename = item.getName();
    System.out.println(filename);
    int index = filename.lastIndexOf("\\");
    filename = filename.substring(index + 1, filename.length());

    long fileSize = item.getSize();

    if ("".equals(filename) && fileSize == 0) {
        throw new RuntimeException("You didn't upload a file.");
        //return;
    }/*from w  w  w .ja v  a2s  . co  m*/

    File uploadFile = new File(filePath + "/" + filename);
    item.write(uploadFile);
    pw.println("<a id=\"filelink\" href=\"" + prefix_url + filename + "\" >Link</a> to the uploaded file : "
            + filename);
    System.out.println(fileSize + "\r\n");
}

From source file:com.app.uploads.ImageTest.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*  w ww. j  a  v 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");
    PrintWriter out = response.getWriter();
    String type = "";
    CallableStatement pro;

    String UPLOAD_DIRECTORY = getServletContext().getRealPath("\\uploads\\");
    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            try {
                String name = "";
                List<FileItem> multiparts;
                multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

                for (FileItem item : multiparts) {
                    if (!item.isFormField()) {
                        name = new File(item.getName()).getName();
                        item.write(new File(UPLOAD_DIRECTORY + File.separator + name));
                    } else if (item.isFormField()) {
                        String fiel = item.getFieldName();
                        InputStream is = item.getInputStream();
                        byte[] b = new byte[is.available()];
                        is.read(b);
                        type = new String(b);
                    }

                }

                //File uploaded successfully
                Connection connect = OracleConnect.getConnect(Dir.Host, Dir.Port, Dir.Service, Dir.UserName,
                        Dir.PassWord);
                pro = connect.prepareCall("{call STILL_INSERT_TEST(?,?)}");
                pro.setInt(1, 2);
                pro.setString(2, name);
                pro.executeQuery();
                pro.close();
                connect.close();
                if (name != null) {
                    request.setAttribute("type", type);
                    request.setAttribute("success", "ok");
                }
            } catch (Exception ex) {
                request.setAttribute("message", "File Upload Failed due to " + ex);
            }

        } else {
            request.setAttribute("message", "Sorry this Servlet only handles file upload request");
        }

        request.getRequestDispatcher("/SearchEngine.jsp").forward(request, response);
    } finally {
        out.close();
    }
}

From source file:com.seer.datacruncher.services.HttpFileUpload.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    try {/* ww w.  ja  va 2s  .  c o  m*/
        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();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            if (!item.isFormField()) {
                String fileName = item.getName();

                String str = getServletContext().getRealPath("/");
                fileName = fileName.substring(0, fileName.indexOf(".")) + ".txt";
                File uploadedFile = new File(str + fileName);
                item.write(uploadedFile);

                out.println("<Status>Success: File has been uploaded at " + uploadedFile.getAbsolutePath()
                        + "</Status>");
                out.flush();
                out.close();

                return;
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    out.println("<Status>Failure</Status>");
    out.flush();
    out.close();
}