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.cwctravel.jenkinsci.plugins.htmlresource.HTMLResourceManagement.java

/**
 * Uploads a script and stores it with the given filename to the configuration. It will be stored on the filessytem.
 * /* w w  w .j a va2  s .  co  m*/
 * @param req
 *        request
 * @return forward to index page.
 * @throws IOException
 * @throws ServletException
 */
public HttpResponse doUploadHTMLResource(StaplerRequest req) throws IOException, ServletException {
    checkPermission(Hudson.ADMINISTER);
    try {

        FileItem fileItem = req.getFileItem("file");
        String fileName = Util.getFileName(fileItem.getName());
        if (StringUtils.isEmpty(fileName)) {
            return new HttpRedirect(".");
        }
        saveHTMLResource(fileItem, fileName);

        return new HttpRedirect("index");
    } catch (IOException e) {
        throw e;
    } catch (Exception e) {
        throw new ServletException(e);
    }
}

From source file:de.betterform.agent.web.servlet.UploadServlet.java

private void uploadFile(HttpServletRequest request, FileItem uploadItem, String relativeUploadPath)
        throws Exception {
    String realPath = WebFactory.getRealPath(".", request.getSession().getServletContext());
    File uploadDirectory = new File(realPath, relativeUploadPath);
    String fileName = uploadItem.getName();
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("uploading file '" + fileName + "' to directory '" + uploadDirectory + "'");
    }//  www.j  av  a 2  s.  com

    File localFile = new File(uploadDirectory.getAbsolutePath(), fileName);

    if (!localFile.getParentFile().exists()) {
        localFile.getParentFile().mkdirs();
    }
    uploadItem.write(localFile);

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("file '" + fileName + "' successfully uploaded to directory '" + uploadDirectory + "'");
    }
}

From source file:id.go.customs.training.gudang.web.BarangUploadServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    Boolean adaFile = ServletFileUpload.isMultipartContent(req);
    if (adaFile) {
        try {//ww  w . j  a  va 2  s.c  o m
            String lokasiLengkap = req.getServletContext().getRealPath(lokasiPenyimpanan);
            System.out.println("Lokasi hasil upload : " + lokasiLengkap);

            // inisialisasi prosesor upload
            DiskFileItemFactory factory = new DiskFileItemFactory();
            File lokasiSementaraHasilUpload = (File) req.getServletContext()
                    .getAttribute("javax.servlet.context.tempdir");
            factory.setRepository(lokasiSementaraHasilUpload);
            System.out.println("Lokasi upload sementara : " + lokasiSementaraHasilUpload.getAbsolutePath());
            ServletFileUpload prosesorUpload = new ServletFileUpload(factory);

            List<FileItem> hasilUpload = prosesorUpload.parseRequest(req);
            System.out.println("Jumlah file = " + hasilUpload.size());

            for (FileItem fileItem : hasilUpload) {
                System.out.println("----- Informasi File -----");
                System.out.println("Tipe File : " + fileItem.getContentType());
                System.out.println("Nama Field : " + fileItem.getFieldName());
                System.out.println("Nama File : " + fileItem.getName());
                System.out.println("Ukuran File : " + fileItem.getSize());

                String fileTujuan = lokasiLengkap + File.separator + fileItem.getName();
                File tujuan = new File(fileTujuan);
                fileItem.write(tujuan);
                System.out.println("Hasil upload ada di " + fileTujuan);

                HasilImportBarang hasil = BarangImporter.importCsv(tujuan);
                req.setAttribute("hasil", hasil);
            }
        } catch (Exception ex) {
            Logger.getLogger(BarangUploadServlet.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    // selesai upload, tampilkan hasil upload
    req.getRequestDispatcher("/WEB-INF/templates/jsp/barang/import.jsp").forward(req, resp);
}

From source file:com.antinymail.ventadecasas.servlet.UploadServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException {
    // Check that we have a file upload request
    isMultipart = ServletFileUpload.isMultipartContent(request);
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    if (!isMultipart) {
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<p>No file uploaded</p>");
        out.println("</body>");
        out.println("</html>");
        return;/* w ww  .  j  ava  2s  .c  o  m*/
    }
    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("c:\\temp"));

    //factory.setRepository(new File("C:\\Users\\Susana\\Documents\\NetBeansProjects\\VentadeCasas\\web\\images")); 

    factory.setRepository(
            new File("C:\\Users\\Susana\\Documents\\NetBeansProjects\\VentadeCasas\\web\\images"));

    //factory.setRepository(new File("//petylde.esy.es//uploads//casapueblo"));
    //factory.setRepository(new Uri());

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);

    // maximum file size to be uploaded.
    upload.setSizeMax(maxFileSize);

    try {
        // Parse the request to get file items.
        List fileItems = upload.parseRequest(request);

        // Process the uploaded file items
        Iterator i = fileItems.iterator();

        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");
        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            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
                if (fileName.lastIndexOf("\\") >= 0) {

                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));

                    //file = new File( fileName);

                } else {
                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));

                    //file = new File( fileName);
                }
                fi.write(file);
                //fi.write( fileNa ) ;  

                out.println("Uploaded Filename: " + fileName + "<br>");
                out.println("La ruta inicial era: " + filePath + "<br>");

            }
        }
        out.println("</body>");
        out.println("</html>");
    } catch (Exception ex) {
        System.out.println(ex);
    }
}

From source file:it.marcoberri.mbmeteo.action.UploadFile.java

/**
 * Handles the HTTP/*  w  ww  .j av  a  2  s.  c  o  m*/
 * <code>POST</code> method.
 *
 * @param request servlet request
 * @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 {

    // checks if the request actually contains upload file
    if (!ServletFileUpload.isMultipartContent(request)) {
        return;
    }

    // configures some settings
    final DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(THRESHOLD_SIZE);
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    final ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setFileSizeMax(MAX_FILE_SIZE);
    upload.setSizeMax(REQUEST_SIZE);

    // constructs the directory path to store upload file
    final String uploadPath = ConfigurationHelper.prop.getProperty("import.loggerEasyWeather.filepath");

    final File uploadDir = new File(uploadPath);

    if (!uploadDir.exists()) {
        FileUtils.forceMkdir(uploadDir);
    }

    try {
        // parses the request's content to extract file data
        final List formItems = upload.parseRequest(request);
        Iterator iter = formItems.iterator();

        // iterates over form's fields
        while (iter.hasNext()) {
            final FileItem item = (FileItem) iter.next();
            // processes only fields that are not form fields
            if (item.isFormField()) {
                continue;
            }

            final String fileName = new File(item.getName()).getName();
            final String filePath = uploadPath + File.separator + fileName;
            final File storeFile = new File(filePath);
            item.write(storeFile);
        }
        request.setAttribute("message", "Upload has been done successfully!");
    } catch (final Exception ex) {
        request.setAttribute("message", "There was an error: " + ex.getMessage());
    }

    final ExecuteImport i = new ExecuteImport();
    Thread t = new Thread(i);
    t.start();

}

From source file:edu.lafayette.metadb.web.controlledvocab.CreateVocab.java

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*///from ww w  .  j  a v  a 2s .  c  o  m
@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // TODO Auto-generated method stub
    PrintWriter out = response.getWriter();
    String vocabName = null;
    String name = "nothing";
    String status = "Upload failed ";

    try {

        if (ServletFileUpload.isMultipartContent(request)) {
            name = "isMultiPart";
            ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
            List fileItemsList = servletFileUpload.parseRequest(request);
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            diskFileItemFactory.setSizeThreshold(40960); /* the unit is bytes */

            InputStream input = null;
            Iterator it = fileItemsList.iterator();
            String result = "";
            String vocabs = null;

            while (it.hasNext()) {
                FileItem fileItem = (FileItem) it.next();
                result += "CreateVocab: Form Field: " + fileItem.isFormField() + " Field name: "
                        + fileItem.getFieldName() + " Name: " + fileItem.getName() + " String: "
                        + fileItem.getString() + "\n";
                if (fileItem.isFormField()) {
                    /* The file item contains a simple name-value pair of a form field */
                    if (fileItem.getFieldName().equals("vocab-name"))
                        vocabName = fileItem.getString();
                    else if (fileItem.getFieldName().equals("vocab-terms"))
                        vocabs = fileItem.getString();
                } else {

                    @SuppressWarnings("unused")
                    String content = "nothing";
                    /* The file item contains an uploaded file */

                    /* Create new File object
                    File uploadedFile = new File("test.txt");
                    if(!uploadedFile.exists())
                       uploadedFile.createNewFile();
                    // Write the uploaded file to the system
                    fileItem.write(uploadedFile);
                    */
                    name = fileItem.getName();
                    content = fileItem.getContentType();
                    input = fileItem.getInputStream();
                }
            }
            //MetaDbHelper.note(result);
            if (vocabName != null) {
                Set<String> vocabList = new TreeSet<String>();
                if (input != null) {
                    Scanner fileSc = new Scanner(input);
                    while (fileSc.hasNextLine()) {
                        String vocabEntry = fileSc.nextLine();
                        vocabList.add(vocabEntry.trim());
                    }

                    HttpSession session = request.getSession(false);
                    if (session != null) {
                        String userName = (String) session.getAttribute("username");
                        SysLogDAO.log(userName, Global.SYSLOG_PROJECT,
                                "User " + userName + " created vocab " + vocabName);
                    }
                    status = "Vocab name: " + vocabName + ". File name: " + name + "\n";

                } else {
                    //               status = "Form is not multi-part";
                    //               vocabName = request.getParameter("vocab-name");
                    //               String vocabs = request.getParameter("vocab-terms");
                    MetaDbHelper.note(vocabs);
                    for (String vocab : vocabs.split("\n"))
                        vocabList.add(vocab);
                }
                if (!vocabList.isEmpty()) {
                    if (ControlledVocabDAO.addControlledVocab(vocabName, vocabList))
                        status = "Vocab " + vocabName + " created successfully";
                    else if (ControlledVocabDAO.updateControlledVocab(vocabName, vocabList))
                        status = "Vocab " + vocabName + " updated successfully ";
                    else
                        status = "Vocab " + vocabName + " cannot be updated/created";
                }
            }
        }
    } catch (Exception e) {
        MetaDbHelper.logEvent(e);
    }
    MetaDbHelper.note(status);
    out.print(status);
    out.flush();
}

From source file:com.skin.generator.action.UploadTestAction.java

/**
 * @throws IOException/*from w  ww.j  av  a 2 s  .  c  om*/
 * @throws ServletException
 */
@UrlPattern("/upload/test2.html")
public void test2() throws IOException, ServletException {
    logger.info("method: " + this.request.getMethod() + " " + this.request.getRequestURI() + " "
            + this.request.getQueryString());

    /**
     * cross domain support
     */
    this.doOptions(this.request, this.response);

    /**
      * preflight
     */
    if (this.request.getMethod().equalsIgnoreCase("OPTIONS")) {
        logger.info("options: " + this.request.getHeader("Origin"));
        return;
    }

    String home = this.servletContext.getRealPath("/WEB-INF/tmp");
    Map<String, Object> result = new HashMap<String, Object>();
    RandomAccessFile raf = null;
    InputStream inputStream = null;

    try {
        Map<String, Object> map = this.parse(this.request);
        int start = Integer.parseInt((String) map.get("start"));
        int end = Integer.parseInt((String) map.get("end"));
        int length = Integer.parseInt((String) map.get("length"));
        FileItem fileItem = (FileItem) map.get("fileData");

        inputStream = fileItem.getInputStream();
        raf = new RandomAccessFile(new File(home, fileItem.getName()), "rw");
        raf.seek(start);
        String partMd5 = copy(inputStream, raf, 4096);

        if (end >= length) {
            String fileMd5 = Hex.encode(Digest.md5(new File(home, fileItem.getName())));
            result.put("fileMd5", fileMd5);
        }

        result.put("status", 200);
        result.put("message", "??");
        result.put("start", end);
        result.put("partMD5", partMd5);
        JsonUtil.callback(this.request, this.response, result);
        return;
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        result.put("status", 500);
        result.put("message", "?");
        JsonUtil.callback(this.request, this.response, result);
        return;
    } finally {
        close(raf);
        close(inputStream);
    }
}

From source file:com.pagoadalabs.fileupload.controller.FileController.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*w w w .  j  a v  a2s  .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 {
    // Check that we have a file upload request
    isMultipart = ServletFileUpload.isMultipartContent(request);
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    if (!isMultipart) {
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<p>No file uploaded</p>");
        out.println("</body>");
        out.println("</html>");
        return;
    }
    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("e://temp"));

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum file size to be uploaded.
    upload.setSizeMax(maxFileSize);

    try {
        // Parse the request to get file items.
        List fileItems = upload.parseRequest(request);

        // Process the uploaded file items
        Iterator i = fileItems.iterator();

        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");
        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            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
                if (fileName.lastIndexOf("\\") >= 0) {
                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
                } else {
                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));
                }
                fi.write(file);
                out.println("Uploaded Filename: " + fileName + "<br>");
            }
        }
        out.println("</body>");
        out.println("</html>");
    } catch (Exception ex) {
        System.out.println(ex);
    }
}

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 a va 2s  . 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.ControllerImage.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//  w  w 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 {

    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);
                    String RealPath = getServletContext().getRealPath("/") + "upload\\" + fileName;
                    String code = (String) params.get("txtCode");
                    String name = (String) params.get("txtName");
                    String price = (String) params.get("txtPrice");
                    int a = Integer.parseInt(price);
                    String image = (String) params.get("txtImage");
                    //Update  product
                    if (fileName.equals("")) {

                        Products sp = new Products();
                        sp.Update(code, name, price, image);
                        RequestDispatcher rd = request.getRequestDispatcher("product.jsp");
                        rd.forward(request, response);

                    } else {
                        // bat dau ghi file
                        File savedFile = new File(RealPath);
                        item.write(savedFile);
                        //ket thuc ghi
                        Products sp = new Products();
                        sp.Update(code, name, price, "upload\\" + fileName);

                        RequestDispatcher rd = request.getRequestDispatcher("product.jsp");
                        rd.forward(request, response);
                    }

                } catch (Exception e) {
                    RequestDispatcher rd = request.getRequestDispatcher("InformationError.jsp");
                    rd.forward(request, response);
                }
            }

        }
    }

    this.processRequest(request, response);

}