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:at.ac.tuwien.dsg.cloudlyra.utils.Uploader.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from   w ww .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 {
    InputStream dafFileContent = null;
    String dafName = "";
    String dafType = "";

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

            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    dafName = new File(item.getName()).getName();
                    dafFileContent = item.getInputStream();

                } else {

                    String fieldName = item.getFieldName();
                    String fieldValue = item.getString();

                    if (fieldName.equals("type")) {
                        dafType = fieldValue;
                    }

                    // String log = "att name: " + fieldname + " - value: " + fieldvalue;
                    // Logger.getLogger(Uploader.class.getName()).log(Level.INFO, log);

                }
            }

            //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");
    }

    if (!dafName.equals("")) {

        DafStore dafStore = new DafStore();
        dafStore.insertDAF(dafName, dafType, dafFileContent);
        Logger.getLogger(Uploader.class.getName()).log(Level.INFO, dafName);
    }

    response.sendRedirect("daf.jsp");
}

From source file:com.silverpeas.attachment.servlets.DragAndDrop.java

private String saveFileOnDisk(FileItem item, String componentId, String context) throws Exception {
    String fileName = item.getName();
    if (fileName != null) {
        fileName = FilenameUtils.separatorsToSystem(fileName);
        SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE", "file = " + fileName);
        String type = FileRepositoryManager.getFileExtension(fileName);
        String physicalName = new Date().getTime() + "." + type;
        File file = new File(AttachmentController.createPath(componentId, context) + physicalName);
        item.write(file);/*w ww  . ja  va  2s.  com*/
        return physicalName;
    }
    return null;
}

From source file:com.stratelia.silverpeas.versioningPeas.servlets.DragAndDrop.java

private String saveFileOnDisk(FileItem item, String componentId, VersioningImportExport vie) throws Exception {
    String fileName = item.getName();
    if (fileName != null) {
        fileName = fileName.replace('\\', File.separatorChar);
        fileName = fileName.replace('/', File.separatorChar);
        SilverTrace.info("versioningPeas", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE",
                "file = " + fileName);

        String type = FileRepositoryManager.getFileExtension(fileName);
        String physicalName = new Date().getTime() + "." + type;
        File savedFile = new File(vie.getVersioningPath(componentId) + physicalName);
        File parent = savedFile.getParentFile();
        if (!parent.exists()) {
            parent.mkdirs();//w w  w  .j a  v  a2  s . com
        }
        item.write(savedFile);
        return physicalName;
    }
    return null;
}

From source file:com.openmeap.model.event.handler.ArchiveFileUploadHandler.java

@Override
public <E extends Event<Map>> void handle(E event) throws ClusterHandlingException {

    Map parms = event.getPayload();
    ApplicationArchive arch = (ApplicationArchive) parms.get("archive");

    String hashId = String.format("{%s}%s", arch.getHashAlgorithm(), arch.getHash());

    logger.debug("ArchiveUploadEvent for file {}", hashId);

    File file = arch.getFile(getFileSystemStoragePathPrefix());

    if (file.exists()) {
        logger.warn("ApplicationArchive with {} hash already exists, ignoring ArchiveUploadEvent.", hashId);
        return;/*from   w  ww  .  j a  va  2s .com*/
    }

    if (parms.get("file") == null || !(parms.get("file") instanceof FileItem)) {
        logger.error(
                "Expected a FileItem under the \"file\" parameter.  Got " + parms.get("file") + " instead.");
        throw new ClusterHandlingException(
                "Expected a FileItem under the \"file\" parameter.  Got " + parms.get("file") + " instead.");
    }

    FileItem item = (FileItem) parms.get("file");
    try {
        item.write(file);
    } catch (Exception ioe) {
        logger.error("An error occurred writing {}: {}", item.getName(), ioe);
        throw new ClusterHandlingException(ioe);
    }
    item.delete();
}

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

/**
 * This API is used to get zip file name.
 * //from w  w w . ja v  a2s. c  o m
 * @param item {@link FileItem} uploaded file item.
 * @return {@link String} zip file name.
 */
private String getZipFileName(final FileItem item) {
    String zipFileName = item.getName();
    if (zipFileName != null) {
        zipFileName = zipFileName.substring(zipFileName.lastIndexOf(File.separator) + 1);
        zipFileName = FilenameUtils.getName(zipFileName);
    }
    return zipFileName;
}

From source file:controller.ProductProcess.java

public String processImage(HttpServletRequest request, HttpServletResponse response) throws IOException {

    if (!ServletFileUpload.isMultipartContent(request)) {
        PrintWriter writer = response.getWriter();
        writer.print("error");
        return "";
    }/*from   w w  w .  j  a va2  s. c o m*/
    String pathh = "";
    DiskFileItemFactory factory = new DiskFileItemFactory(MEMORY_THRESHOLD,
            new File(System.getProperty("java.io.tmpdir")));

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

    String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;

    File uploadDir = new File(uploadPath);
    if (!uploadDir.exists()) {
        uploadDir.mkdir();
    }

    try {
        List<FileItem> formItems = upload.parseRequest(request);

        if (formItems != null && formItems.size() > 0) {
            for (FileItem formItem : formItems) {
                if (!formItem.isFormField()) {
                    String a = formItem.getName();
                    String fileName = new File(a).getName();
                    pathh = fileName;
                    String filePath = uploadPath + File.separator + fileName;

                    File storeFile = new File(filePath);

                    formItem.write(storeFile);
                } else {
                    String nameAttribute = formItem.getFieldName();
                    String valueAttribute = formItem.getString("UTF-8");
                    request.setAttribute(nameAttribute, valueAttribute);
                }
            }

        }

    } catch (Exception e) {
        e.printStackTrace();
        return "";
    }

    return pathh;
}

From source file:au.edu.unimelb.news.servlet.ImportServlet.java

/**
 * Reads all user input related to creating a new agenda item and creates the agenda item.
 *///from ww  w.j a va2s  .c  om
@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    User user = UserHelper.getUser(request);
    response.setContentType("text/html");
    PrintWriter out = new PrintWriter(response.getOutputStream());
    LayoutHelper.headerTitled(out, "Import");
    LayoutHelper.menubar(out, user);

    out.println("<div id=\"breadcrumbs\">");
    out.println("<a href=\"http://www.unimelb.edu.au\">University home</a> &gt;");
    out.println("<a href=\"" + Configuration.appPrefix + "/\">University News</a> &gt;");
    out.println("Document Import");
    out.println("</div>");

    out.println("<div id=\"content\">");
    out.println("<h2>Importing</h2>");

    //out.flush();

    /*
     *  This chunk calls the Jakarta Commons Fileupload component to
     *  process the file upload information.
     */
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    List<FileItem> items = null;
    try {
        items = upload.parseRequest(request);
    } catch (Exception e) {
        out.println("Fatal error: " + e.getMessage());
        out.println("</div>");
        LayoutHelper.footer(out);

        out.flush();
        out.close();
    }

    /*
     * Use the Jakarta Commons Fileupload component to read the
     * field variables.
     */
    try {
        out.println("<ul>");
        String filename = "";
        for (FileItem field : items) {
            if (!field.isFormField()) {
                filename = field.getName();
                if (filename.contains("/"))
                    filename = filename.substring(filename.lastIndexOf('/') + 1);
                if (filename.contains("\\"))
                    filename = filename.substring(filename.lastIndexOf('\\') + 1);
                int no = random.nextInt();
                if (no < 1)
                    no = -no;
                if (filename.length() > 0 && field.getSize() > 0
                        && field.getFieldName().equals("import_file")) {
                    ArticleImport helper = new ArticleImport(new ArticleImportResponder(user, out));
                    helper.process(field.getInputStream(), user);
                }
            }
        }
        out.println("</ul>");
    } catch (Exception e) {
        out.println("Fatal error: " + e.getMessage());
        out.println("</div>");
        LayoutHelper.footer(out);

        out.flush();
        out.close();
    }

    out.println("File upload processing complete.");

    out.println("</div>");
    LayoutHelper.footer(out);

    out.flush();
    out.close();
}

From source file:com.fatih.edu.tr.NewTaskServlet.java

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

    // Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (!isMultipart) {
        return;//from   w w w .j av a 2  s .com
    }

    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();

    // Sets the size threshold beyond which files are written directly to
    // disk.
    factory.setSizeThreshold(MAX_MEMORY_SIZE);

    // Sets the directory used to temporarily store files that are larger
    // than the configured size threshold. We use temporary directory for
    // java
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    // constructs the folder where uploaded file will be stored
    String uploadFolder = getServletContext().getRealPath("") + File.separator + DATA_DIRECTORY;

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

    // Set overall request size constraint
    upload.setSizeMax(MAX_REQUEST_SIZE);

    TaskDao taskDao = new TaskDao();
    String title = "";
    String description = "";
    String due_date = "";
    String fileName = "";
    String filePath = "";
    //taskDao.addTask(title, description, due_date, "testfile","testdizi",1);

    try {
        // Parse the request
        List items = upload.parseRequest(request);
        Iterator iter = items.iterator();
        while (iter.hasNext()) {

            FileItem item = (FileItem) iter.next();

            if (!item.isFormField()) {
                fileName = new File(item.getName()).getName();
                filePath = uploadFolder + File.separator + fileName;
                File uploadedFile = new File(filePath);
                System.out.println(filePath);
                item.write(uploadedFile);
            } else {
                String fieldname = item.getFieldName();
                String fieldvalue = item.getString();
                if (fieldname.equals("title")) {
                    title = item.getString();
                } else if (fieldname.equals("description")) {
                    description = item.getString();

                } else if (fieldname.equals("due_date")) {
                    due_date = item.getString();
                } else {
                    System.out.println("Something goes wrong in form");
                }
            }

        }
        taskDao.addTask(title, description, due_date, fileName, filePath, 1);
        // displays done.jsp page after upload finished
        getServletContext().getRequestDispatcher("/done.jsp").forward(request, response);

    } catch (FileUploadException ex) {
        throw new ServletException(ex);
    } catch (Exception ex) {
        throw new ServletException(ex);
    }

}

From source file:com.Voxce.DAO.MedicalLicenseDAO.java

public int UploadMedicalLicense(FileItem item, MedicalLicense medicallicense, int idnum) {

    if (item != null) {
        medicallicense.setData(item.get());
        medicallicense.setFilename(item.getName());
        medicallicense.setType(item.getContentType());
    }// ww w.  ja  v  a  2 s  . c  o  m
    if (idnum == 0) {
        Calendar cal = Calendar.getInstance();
        Date oneDate = new java.sql.Date(cal.getTime().getTime());

        medicallicense.setDate_created(oneDate);
        medicallicense.setDate_modified(oneDate);
        try {
            data = hibernateTemplate.find("FROM MedicalLicense WHERE site_id='" + medicallicense.getSite_id()
                    + "' AND study_id='" + medicallicense.getStudy_id() + "' AND user_id='"
                    + medicallicense.getUser_id() + "' AND begin_dt='" + medicallicense.getBegin_dt()
                    + "' AND start_dt='" + medicallicense.getStart_dt() + "' AND expire_dt='"
                    + medicallicense.getExpire_dt() + "'");

        } catch (Exception e) {
            e.printStackTrace();
        }

        if (data.size() != 0) {
            System.out.println("Record Found");
            return 0;
        }
        // Code Does not Exists //
        else if (data.size() == 0) {
            hibernateTemplate.saveOrUpdate(medicallicense);

            return 1;
        }
    } else {
        Calendar cal = Calendar.getInstance();
        Date oneDate = new java.sql.Date(cal.getTime().getTime());
        medicallicense.setDate_modified(oneDate);

        try {
            System.out.println("editing...");
            hibernateTemplate.saveOrUpdate(medicallicense);

            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
    return 0;

}

From source file:filter.MultipartRequestFilter.java

/**
 * Process multipart request item as file field. The name and FileItem object of each file field
 * will be added as attribute of the given HttpServletRequest. If a FileUploadException has
 * occurred when the file size has exceeded the maximum file size, then the FileUploadException
 * will be added as attribute value instead of the FileItem object.
 * @param fileField The file field to be processed.
 * @param request The involved HttpServletRequest.
 *//*www.  j a va  2  s  .  com*/
private void processFileField(FileItem fileField, HttpServletRequest request) {
    if (fileField.getName().length() <= 0) {
        // No file uploaded.
        addAttributeValue(request, fileField.getFieldName(), null);
    } else if (maxFileSize > 0 && fileField.getSize() > maxFileSize) {
        // File size exceeds maximum file size.
        addAttributeValue(request, fileField.getFieldName(),
                new FileUploadException("File size exceeds maximum file size of " + maxFileSize + " bytes."));
        // Immediately delete temporary file to free up memory and/or disk space.
        fileField.delete();
    } else {
        // File uploaded with good size.
        addAttributeValue(request, fileField.getFieldName(), fileField);
    }
}