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:com.es.keyassistant.resolvers.Resolver0004.java

@Override
public ServiceResult execute() throws Exception {
    File dir = new File(getRequest().getServletContext().getRealPath(TMP_PATH));
    dir.mkdirs();/*from   ww  w  . j  a  v  a  2 s  .  c om*/

    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(5 * 1024);
    factory.setRepository(dir);
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("UTF-8");
    upload.setSizeMax(5 * 1024 * 1024);
    List<FileItem> formItems = upload.parseRequest(getRequest());

    DetectionInfo info = new DetectionInfo();
    assignPropertiesTo(formItems, info);

    for (FileItem formItem : formItems) {
        if (!formItem.isFormField()) {
            String fileName = formItem.getName();
            String targetFileName = generateDectionFileName(fileName, info);
            info.setDetectionFileName(targetFileName);
            info.setDetectionFilePath(String.format("%s/%s", STORE_PATH, targetFileName));

            File storeDir = new File(getRequest().getServletContext().getRealPath(STORE_PATH));
            storeDir.mkdirs();
            File detectionFile = new File(storeDir, targetFileName);

            formItem.write(detectionFile);

            formItem.delete();
            break;
        }
    }

    if (info.getDetectionSN() == null) {
        throw new ClientException(ClientException.REQUEST_ERROR, "");
    }

    ContentService service = new ContentService();
    if (service.addDetectionInfo(info) < 0) {
        throw new ClientException(ClientException.REQUEST_ERROR, "??");
    }

    ServiceResult result = new ServiceResult();
    result.getData().add(makeMapByKeyAndValues("receiptNumber", info.getDetectionSN()));

    return result;
}

From source file:Controlador.UploadController.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    //verificar el multipart/form-data
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    String name = request.getParameter("name");
    try (PrintWriter out = response.getWriter()) {
        out.println("Nombre: " + name);
        if (isMultipart) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            try {
                List 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("/imagenes/");
                        File path = new File(root);
                        if (!path.exists()) {
                            boolean status = path.mkdirs();
                        }//from   www .  j  a va 2s. com

                        File uploadedFile = new File(path + "/" + fileName);
                        out.println(uploadedFile.getAbsolutePath());
                        item.write(uploadedFile);
                    }
                }
            } catch (FileUploadException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:controller.uploadPergunta9.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.// w  w  w .j  av a2 s .  c om
 *
 * @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 {

    String idLocal = (String) request.getParameter("idLocal");
    String idModelo = (String) request.getParameter("idModelo");
    String expressaoModelo = (String) request.getParameter("expressaoModelo");
    String nomeAutorModelo = (String) request.getParameter("nomeAutorModelo");
    String equacaoAjustada = (String) request.getParameter("equacaoAjustada");
    String idEquacaoAjustada = (String) request.getParameter("idEquacaoAjustada");

    String name = "";
    //process only if its multipart content
    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(UPLOAD_DIRECTORY + File.separator + name));
                    item.write(new File(AbsolutePath + File.separator + name));
                }
            }

            //File uploaded successfully
            request.setAttribute("message", "File Uploaded Successfully");
        } catch (Exception ex) {
            request.setAttribute("message", "File Upload Failed due to " + ex);
        }

    } else {
        request.setAttribute("message", "Sorry this Servlet only handles file upload request");
    }
    equacaoAjustada = equacaoAjustada.replace("+", "%2B");
    expressaoModelo = expressaoModelo.replace("+", "%2B");
    RequestDispatcher view = getServletContext()
            .getRequestDispatcher("/novoLocalPergunta9?id=" + idLocal + "&nomeArquivo=" + name + "&idModelo="
                    + idModelo + "&equacaoAjustada=" + equacaoAjustada + "&expressaoModelo=" + expressaoModelo
                    + "&nomeAutorModelo=" + nomeAutorModelo + "&idEquacaoAjustada=" + idEquacaoAjustada);
    view.forward(request, response);

    //        request.getRequestDispatcher("/novoLocalPergunta3?id="+idLocal+"&fupload=1&nomeArquivo="+name).forward(request, response);
    // request.getRequestDispatcher("/novoLocalPergunta4?id="+idLocal+"&nomeArquivo="+name).forward(request, response);

}

From source file:com.skin.taurus.http.servlet.UploadServlet.java

/**
 * @param item//from w  ww .  ja v  a2 s.  c  om
 * @throws Exception
 */
private String save(FileItem item) throws Exception {
    String fileName = this.getFileName(item.getName());
    String extension = this.getFileExtensionName(fileName);

    if (logger.isDebugEnabled()) {
        logger.debug("Client File: " + item.getName());
        logger.debug("ContentType: " + item.getContentType());
        logger.debug("Field Name : " + item.getFieldName());
        logger.debug("File Name  : " + fileName);
        logger.debug("Extension  : " + extension);
    }

    int i = 1;
    String shortName = fileName.substring(0, fileName.length() - extension.length());
    File file = null;

    do {
        file = new File("./upload/" + shortName + "_" + (i) + extension);
        i++;
    } while (file.exists());

    if (logger.isDebugEnabled()) {
        logger.debug("Save " + fileName + " To " + file.getAbsolutePath());
    }

    item.write(file);

    return file.getCanonicalPath();
}

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

protected void _serializeUploadedFiles(List<FileItem> fileItemsList, String jobId,
        Map<String, String> uploadedFiles, Map<String, String> uploadedFilesPaths, String repFolderPath)
        throws Exception {

    Iterator<FileItem> fileItemsIterator = fileItemsList.iterator();
    while (fileItemsIterator.hasNext()) {
        FileItem fileItem = fileItemsIterator.next();
        String fileName = fileItem.getName();
        if (fileName == null) {
            ResourceErrorHandler.handleError("A valid file name was not specified.", Status.BAD_REQUEST, log);
        }//w w w  .j  a va2  s. co m

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

        String[] nameParts = fileName.split("\\.");
        if (nameParts.length > 1) {
            String extension = nameParts[nameParts.length - 1].toUpperCase();

            String[] subArr = ArrayUtils.removeElement(nameParts, nameParts[nameParts.length - 1]);
            String filename = StringUtils.join(subArr, '.');
            if (extension.equalsIgnoreCase("OSM") || extension.equalsIgnoreCase("SHP")
                    || extension.equalsIgnoreCase("ZIP")) {
                uploadedFiles.put(filename, extension);
                uploadedFilesPaths.put(filename, fileName);
                log.debug("Saving uploaded:" + filename);
            }

        }

    }
}

From source file:com.cloudbees.api.BeesClientTruProxyTest.java

@Test
public void deployWarArchive() throws Exception {
    CloudbeesServer cloudbeesServer = new CloudbeesServer();
    cloudbeesServer.startServer();/*from ww w .  java2 s  .  co m*/
    File local = new File("src/test/translate-puzzle-webapp-1.0.0-SNAPSHOT.war");
    File uploaded = File.createTempFile("uploaded", "foo");
    assertThat("We have the file to upload", local.isFile(), is(true));
    assertThat("We have created the temp file to be uploaded", uploaded.isFile(), is(true));
    assertThat("Precondition", local.length(), not(is(uploaded.length())));
    try {
        BeesClientConfiguration beesClientConfiguration = new BeesClientConfiguration(
                "http://localhost:" + cloudbeesServer.getPort() + "/", "foo", "bar", "xml", "1.0");
        BeesClient beesClient = new BeesClient(beesClientConfiguration);
        beesClient.setVerbose(true);
        MockUploadProgress mockUploadProgress = new MockUploadProgress();

        beesClient.applicationDeployWar("fooId", "env", "desc", local, null, mockUploadProgress);
        assertNotNull(cloudbeesServer.cloudbessServlet.items);
        int realFilesNumber = 0;

        for (FileItem fileItem : cloudbeesServer.cloudbessServlet.items) {
            log.info("fileItem " + fileItem.getName() + ", size " + fileItem.getSize());
            if (fileItem.getName() != null) {
                realFilesNumber++;
                fileItem.write(uploaded);
            }
        }
        assertEquals(1, realFilesNumber);
        assertThat("Postcondition", local.length(), is(uploaded.length()));
    } catch (Exception e) {
        throw e;
    } finally {
        cloudbeesServer.stopServer();
        uploaded.delete();
    }
}

From source file:com.wabacus.util.TestFileUploadInterceptor.java

public boolean beforeFileUpload(HttpServletRequest request, FileItem fileitemObj,
        Map<String, String> mFormAndConfigValues, PrintWriter out) {

    try {/*from w  w w . j a  va2s.c o m*/

        String filename = fileitemObj.getName();

        // System.out.println("--------------??"+filename);
        if (filename != null && !filename.trim().equals("")) {
            int pos = filename.lastIndexOf("\\");
            filename = filename.substring(pos + 1);
            String[] filenameSplit = filename.split("\\.");
            if (filenameSplit != null && filenameSplit.length > 0) {
                Calendar ca = Calendar.getInstance();
                filename = filenameSplit[0] + "(" + ca.get(Calendar.YEAR) + (ca.get(Calendar.MONTH) + 1)
                        + ca.get(Calendar.DATE) + ca.get(Calendar.HOUR_OF_DAY) + ca.get(Calendar.MINUTE)
                        + ca.get(Calendar.SECOND) + ")" + "." + filenameSplit[1];
                // + ca.get(Calendar.MILLISECOND)      
                mFormAndConfigValues.put(FILENAME_KEY, filename);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return true;// ?      
}

From source file:com.lp.webapp.cc.CCOrderResponseServlet.java

private CreateOrderResult processEjbOrder(HttpServletResponse response, FileItem file) {
    myLogger.info("Receiving post with filename '" + file.getName() + "' (" + file.getSize() + ") bytes.");

    AuftragFacBeanRest a = new AuftragFacBeanRest();
    CreateOrderResult result = a.createOrder(authHeader, new String(file.get()));

    myLogger.info("Processed post with filename '" + file.getName() + "'. Status " + result.getRc());
    return result;
}

From source file:fr.paris.lutece.portal.web.upload.UploadServlet.java

/**
 * {@inheritDoc}/*from w  w  w.j  av  a2  s.c o  m*/
 */
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse response)
        throws ServletException, IOException {
    MultipartHttpServletRequest request = (MultipartHttpServletRequest) req;

    List<FileItem> listFileItems = new ArrayList<FileItem>();
    JSONObject json = new JSONObject();
    json.element(JSON_FILES, new JSONArray());

    for (Entry<String, FileItem> entry : ((Map<String, FileItem>) request.getFileMap()).entrySet()) {
        FileItem fileItem = entry.getValue();

        JSONObject jsonFile = new JSONObject();
        jsonFile.element(JSON_FILE_NAME, fileItem.getName());
        jsonFile.element(JSON_FILE_SIZE, fileItem.getSize());

        // add to existing array
        json.accumulate(JSON_FILES, jsonFile);

        listFileItems.add(fileItem);
    }

    IAsynchronousUploadHandler handler = getHandler(request);

    if (handler == null) {
        AppLogService.error("No handler found, removing temporary files");

        for (FileItem fileItem : listFileItems) {
            fileItem.delete();
        }
    } else {
        handler.process(request, response, json, listFileItems);
    }

    if (AppLogService.isDebugEnabled()) {
        AppLogService.debug("Aysnchronous upload : " + json.toString());
    }

    response.getOutputStream().print(json.toString());
}

From source file:com.kunal.NewServlet2.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   w w  w .j  a  v  a 2s .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 {
    if (ServletFileUpload.isMultipartContent(request)) {

        try {
            HttpSession session = request.getSession();
            String V_Str_Id = (String) session.getAttribute("VSID");
            String containerName = V_Str_Id;
            //String fileName = "Ad2";
            String userId = "7f7a82c6a2464a45b0ea5b7c65c90f38";
            String password = "lM_EC#0a7U})SE-.";
            String auth_url = "https://lon-identity.open.softlayer.com" + "/v3";
            String domain = "1090141";
            String project = "object_storage_e32c650b_e512_4e44_aeb8_c49fdf1de69f";
            Identifier domainIdent = Identifier.byName(domain);
            Identifier projectIdent = Identifier.byName(project);

            OSClient os = OSFactory.builderV3().endpoint(auth_url).credentials(userId, password)
                    .scopeToProject(projectIdent, domainIdent).authenticate();

            SwiftAccount account = os.objectStorage().account().get();
            ObjectStorageService objectStorage = os.objectStorage();
            List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    String name = new File(item.getName()).getName();
                    System.out.println(name);
                    // item.write( new File(UPLOAD_DIRECTORY + File.separator + name));
                    String etag = os.objectStorage().objects().put(containerName, name,
                            Payloads.create(item.getInputStream()));
                    System.out.println(etag);
                }
            }

            //File uploaded successfully
            request.setAttribute("message", "File Uploaded Successfully");
        } 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("/Pre_Installation.jsp").forward(request, response);

}