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:it.unisa.tirocinio.servlet.UploadInformationForModuleFilesServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from www  .  j  a v  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, JSONException {

    try {
        response.setContentType("text/html;charset=UTF-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        out = response.getWriter();
        isMultipart = ServletFileUpload.isMultipartContent(request);
        AdministratorDBOperation getSerialNumberObj = new AdministratorDBOperation();
        ConcreteStaff aAdmin = null;
        String serialNumber = null;
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List fileItems = upload.parseRequest(request);
        Iterator i = fileItems.iterator();
        File fileToStore = null;
        String adminSubfolderPath = filePath;
        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            if (!fi.isFormField()) {
                // Get the uploaded file parameters
                String fieldName = fi.getFieldName();
                String fileName = fi.getName();
                DateFormat dateFormat = new SimpleDateFormat("yyyy");
                Date date = new Date();
                if (fieldName.equals("modulefile")) {
                    fileToStore = new File(
                            adminSubfolderPath + fileSeparator + dateFormat.format(date) + " - Module.pdf");
                } else if (fieldName.equals("registerfile")) {
                    fileToStore = new File(
                            adminSubfolderPath + fileSeparator + dateFormat.format(date) + " - Register.pdf");
                }
                fi.write(fileToStore);
                // out.println("Uploaded Filename: " + fieldName + "<br>");
            } else {
                //out.println("It's not formfield");
                //out.println(fi.getString());
                aAdmin = getSerialNumberObj.getFK_DepartimentbyFK_Account(Integer.parseInt(fi.getString()));
                serialNumber = "" + aAdmin.getFKDepartment();
                adminSubfolderPath += fileSeparator + serialNumber;
                new File(adminSubfolderPath).mkdir();
            }
        }
        message.put("status", 1);
        out.print(message.toString());
    } catch (IOException ex) {
        message.put("status", 0);
        message.put("errorMessage", ex);
        out.print(message.toString());
        Logger.getLogger(UploadInformationFilesServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ClassNotFoundException ex) {
        message.put("status", 0);
        message.put("errorMessage", ex);
        out.print(message.toString());
        Logger.getLogger(UploadInformationFilesServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        message.put("status", 0);
        message.put("errorMessage", ex);
        out.print(message.toString());
        Logger.getLogger(UploadInformationFilesServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (FileUploadException ex) {
        message.put("status", 0);
        message.put("errorMessage", ex);
        out.print(message.toString());
        Logger.getLogger(UploadInformationFilesServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        message.put("status", 0);
        message.put("errorMessage", ex);
        out.print(message.toString());
        Logger.getLogger(UploadInformationFilesServlet.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        out.close();
    }
}

From source file:edu.lternet.pasta.portal.UploadEvaluateServlet.java

/**
 * Process the uploaded file//  ww  w. jav a  2  s . c o m
 * 
 * @param item The multipart form file data.
 * 
 * @return The uploaded file as File object.
 * 
 * @throws Exception
 */
private File processUploadedFile(FileItem item) throws Exception {

    File eml = null;

    // Process a file upload
    if (!item.isFormField()) {

        // Get object information
        String fieldName = item.getFieldName();
        String fileName = item.getName();
        String contentType = item.getContentType();
        boolean isInMemory = item.isInMemory();
        long sizeInBytes = item.getSize();

        String tmpdir = System.getProperty("java.io.tmpdir");

        logger.debug("FILE: " + tmpdir + "/" + fileName);

        eml = new File(tmpdir + "/" + fileName);

        item.write(eml);

    }

    return eml;
}

From source file:com.globalsight.everest.webapp.pagehandler.administration.vendors.VendorHelper.java

/**
 * Save the request parameters from the CV/Resume page
 *///from   ww w.  j a v  a  2 s .  c om
public static void saveCV(Vendor vendor, HttpServletRequest request) throws EnvoyServletException {
    // Create a new file upload handler
    DiskFileUpload upload = new DiskFileUpload();

    String radioValue = null;
    String resumeText = null;
    boolean doUpload = false;
    byte[] data = null;
    String filename = null;
    // Parse the request
    try {
        List /* FileItem */ items = upload.parseRequest(request);
        // Process the uploaded items
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (item.isFormField()) {
                String name = item.getFieldName();
                String value = EditUtil.utf8ToUnicode(item.getString());
                if (name.equals("radioBtn")) {
                    radioValue = value;
                } else if (name.equals("resumeText")) {
                    resumeText = value;
                }
            } else {
                filename = item.getName();
                if (filename == null || filename.equals("")) {
                    // user hit done button but didn't modify the page
                    continue;
                } else {
                    doUpload = true;
                    data = item.get();
                }
            }
        }
        if (radioValue != null) {
            if (radioValue.equals("doc") && doUpload) {
                vendor.setResume(filename, data);
                try {
                    ServerProxy.getVendorManagement().saveResumeFile(vendor);
                } catch (Exception e) {
                    throw new EnvoyServletException(e);
                }
            } else if (radioValue.equals("text")) {
                vendor.setResume(resumeText);
            }
        }
    } catch (FileUploadException fe) {
        throw new EnvoyServletException(fe);
    }
}

From source file:com.picdrop.service.implementation.FileResourceService.java

protected void validateFileItem(FileItem file) throws ApplicationException {
    if (file.getName().length() > 1024) {
        throw new ApplicationException().code(ErrorMessageCode.BAD_RESOURCE_NAME)
                .devMessage(String.format("Recorded file name length (%d/1024)'", file.getName().length()))
                .status(400);//from w ww  . j  a  va 2s  . c  o  m
    }
}

From source file:eu.stratosphere.client.web.JobsServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // check, if we are doing the right request
    if (!ServletFileUpload.isMultipartContent(req)) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;/*w ww  .ja  v a  2s . c o  m*/
    }

    // create the disk file factory, limiting the file size to 20 MB
    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
    fileItemFactory.setSizeThreshold(20 * 1024 * 1024); // 20 MB
    fileItemFactory.setRepository(tmpDir);

    String filename = null;

    // parse the request
    ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
    try {
        @SuppressWarnings("unchecked")
        Iterator<FileItem> itr = ((List<FileItem>) uploadHandler.parseRequest(req)).iterator();

        // go over the form fields and look for our file
        while (itr.hasNext()) {
            FileItem item = itr.next();
            if (!item.isFormField()) {
                if (item.getFieldName().equals("upload_jar_file")) {

                    // found the file, store it to the specified location
                    filename = item.getName();
                    File file = new File(destinationDir, filename);
                    item.write(file);
                    break;
                }
            }
        }
    } catch (FileUploadException ex) {
        resp.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Invalid Fileupload.");
        return;
    } catch (Exception ex) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "An unknown error occurred during the file upload.");
        return;
    }

    // write the okay message
    resp.sendRedirect(targetPage);
}

From source file:net.formio.upload.MultipartRequestPreprocessor.java

private void convertToMaps(List<FileItem> fileItems) {
    for (FileItem item : fileItems) {
        String cts = item.getContentType();

        if (!item.isFormField()) {
            // not simple form field
            String filename = item.getName();
            long size = item.getSize(); // size in bytes
            // some browsers are sending "files" even if none is selected?
            if (size == 0
                    && ((cts == null || cts.isEmpty()) || "application/octet-stream".equalsIgnoreCase(cts))
                    && (filename == null || filename.isEmpty()))
                continue;

            String fileNameLastPart = filename;
            if (filename != null) {
                Matcher m = EXTRACT_LASTPART_PATTERN.matcher(filename);
                if (m.matches()) {
                    fileNameLastPart = m.group(1);
                }//  w ww  .j a  v  a 2  s .c  o m
            }
            String mime = cts;
            if (mime == null) {
                mime = guessContentType(filename);
            }

            RequestUploadedFile file = new RequestUploadedFile(fileNameLastPart, mime, size, item);
            if (fileParams.get(item.getFieldName()) != null) {
                addMultivaluedFile(file, item);
            } else {
                addSingleValueFile(file, item);
            }
        } else {
            if (regularParams.get(item.getFieldName()) != null) {
                addMultivaluedItem(item);
            } else {
                addSingleValueItem(item);
            }
        }
    }
}

From source file:bijian.util.upload.MyMultiPartRequest.java

private void processFileField(FileItem item) {
    LOG.debug("Item is a file upload");

    // Skip file uploads that don't have a file name - meaning that no file was selected.
    if (item.getName() == null || item.getName().trim().length() < 1) {
        LOG.debug("No file has been uploaded for the field: " + item.getFieldName());
        return;/*from   w  ww .j ava  2  s .co m*/
    }

    List<FileItem> values;
    if (files.get(item.getFieldName()) != null) {
        values = files.get(item.getFieldName());
    } else {
        values = new ArrayList<FileItem>();
    }

    values.add(item);
    files.put(item.getFieldName(), values);
}

From source file:controller.Upload.java

/**
 * Servlet implementation class UploadServlet
 *///from   w ww.j a va  2  s.  c  o  m
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpSession session = request.getSession();
    // Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (!isMultipart) {
        return;
    }

    // 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);
    String fileName = "", newname = "";
    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 = (String)session.getId() + new File(item.getName()).getName();
                //                    String filePath = uploadFolder + File.separator + fileName;
                fileName = new File(item.getName()).getName();
                newname = (String) session.getId() + fileName.substring(fileName.lastIndexOf("."));
                String filePath = uploadFolder + File.separator + newname;
                File uploadedFile = new File(filePath);
                System.out.println(filePath);
                // saves the file to upload directory
                item.write(uploadedFile);
            }
        }
        userDao ud = new userDao();
        ud.changeuserpic((int) session.getAttribute("userID"), newname);
        // 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:controller.uploadProductController.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from  w ww .  j a v a2  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 {
    HttpSession session = request.getSession(true);
    String userPath = request.getServletPath();
    if (userPath.equals("/uploadProduct")) {
        boolean success = true;
        // configures upload settings
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // sets memory threshold - beyond which files are stored in disk
        factory.setSizeThreshold(MEMORY_THRESHOLD);
        // sets temporary location to store files
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

        ServletFileUpload upload = new ServletFileUpload(factory);

        // sets maximum size of upload file
        upload.setFileSizeMax(MAX_FILE_SIZE);

        // sets maximum size of request (include file + form data)
        upload.setSizeMax(MAX_REQUEST_SIZE);

        // constructs the directory path to store upload file
        // this path is relative to application's directory
        String uploadPath = getServletContext().getInitParameter("upload.location");
        //creates a HashMap of all inputs
        HashMap hashMap = new HashMap();
        String productId = UUID.randomUUID().toString();
        try {
            @SuppressWarnings("unchecked")
            List<FileItem> formItems = upload.parseRequest(request);
            for (FileItem item : formItems) {
                // processes only fields that are not form fields
                if (!item.isFormField()) {
                    File file = new File(item.getName());
                    File file2 = new File(productId + ".jpg");
                    String filePath = uploadPath + File.separator + file.getName();
                    // saves the file on disk
                    File storeFile = new File(filePath);
                    item.write(storeFile);
                    File rename = new File(filePath);
                    boolean flag = rename.renameTo(file2);
                } else {
                    hashMap.put(item.getFieldName(), item.getString());
                }
            }
        } catch (FileUploadException ex) {
            Logger.getLogger(uploadProductController.class.getName()).log(Level.SEVERE, null, ex);
            request.setAttribute("error", true);
            request.setAttribute("errorMessage", ex.getMessage());
            success = false;
        } catch (Exception ex) {
            Logger.getLogger(uploadProductController.class.getName()).log(Level.SEVERE, null, ex);
            request.setAttribute("error", true);
            request.setAttribute("errorMessage", ex.getMessage());
            success = false;
        }
        String owner = (String) session.getAttribute("customerEmail");
        if (owner == null) {
            owner = "shop";
        }

        String pName = hashMap.get("pName").toString();
        String mNo = hashMap.get("mNo").toString();
        String brand = hashMap.get("brand").toString();
        String description = hashMap.get("description").toString();
        String quantity = hashMap.get("quantity").toString();
        String price = hashMap.get("price").toString();
        String addInfo = hashMap.get("addInfo").toString();
        int categoryId = Integer.parseInt(hashMap.get("category").toString());

        ProductDAO productDAO = new ProductDAOImpl();
        Product product;

        try {
            double priceDouble = Double.parseDouble(price);
            int quantityInt = Integer.parseInt(quantity);
            Category category = (new CategoryDAOImpl()).getCategoryFromID(categoryId);
            if (owner.equals("shop")) {
                product = new Product(productId, pName, mNo, category, quantityInt, priceDouble, brand,
                        description, addInfo, true, true, owner);
            } else {
                product = new Product(productId, pName, mNo, category, quantityInt, priceDouble, brand,
                        description, addInfo, false, false, owner);
            }

            if (!(productDAO.addProduct(product, category.getName()))) {
                throw new Exception("update unsuccessful");
            }
        } catch (Exception e) {
            request.setAttribute("error", true);
            request.setAttribute("errorMessage", e.getMessage());
            success = false;
        }

        request.setAttribute("pName", pName);
        request.setAttribute("mNo", mNo);
        request.setAttribute("brand", brand);
        request.setAttribute("description", description);
        request.setAttribute("quantity", quantity);
        request.setAttribute("price", price);
        request.setAttribute("addInfo", addInfo);
        request.setAttribute("categoryId", categoryId);
        request.setAttribute("success", success);
        if (success == true) {
            request.setAttribute("error", false);
            request.setAttribute("errorMessage", null);
        }
        String url;
        if (owner.equals("shop")) {
            url = "/WEB-INF/view/adminAddProducts.jsp";
        } else {
            url = "/WEB-INF/view/clientSideView/addRecycleProduct.jsp";
        }
        try {
            request.getRequestDispatcher(url).forward(request, response);
        } catch (ServletException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }

}

From source file:com.amalto.core.servlet.UploadFile.java

private void uploadFile(HttpServletRequest req, Writer writer) throws ServletException, IOException {
    // upload file
    if (!ServletFileUpload.isMultipartContent(req)) {
        throw new ServletException("Upload File Error: the request is not multipart!"); //$NON-NLS-1$
    }/*from ww w . j  av  a2  s  .  c  o m*/
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload();

    // Set upload parameters
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(0);
    upload.setFileItemFactory(factory);
    upload.setSizeMax(-1);

    // Parse the request
    List<FileItem> items;
    try {
        items = upload.parseRequest(req);
    } catch (Exception e) {
        throw new ServletException(e.getMessage(), e);
    }

    // Process the uploaded items
    if (items != null && items.size() > 0) {
        // Only one file
        Iterator<FileItem> iter = items.iterator();
        FileItem item = iter.next();
        if (LOG.isDebugEnabled()) {
            LOG.debug(item.getFieldName());
        }

        File file = null;
        if (!item.isFormField()) {
            try {
                String filename = item.getName();
                if (req.getParameter(PARAMETER_DEPLOY_JOB) != null) {
                    String contextStr = req.getParameter(PARAMETER_CONTEXT);
                    file = writeJobFile(item, filename, contextStr);
                } else if (filename.endsWith(".bar")) { //$NON-NLS-1$
                    file = writeWorkflowFile(item, filename);
                } else {
                    throw new IllegalArgumentException("Unknown deployment for file '" + filename + "'"); //$NON-NLS-1$ //$NON-NLS-2$
                }
            } catch (Exception e) {
                throw new ServletException(e.getMessage(), e);
            }
        } else {
            throw new ServletException("Couldn't process request"); //$NON-NLS-1$);
        }
        String urlRedirect = req.getParameter("urlRedirect"); //$NON-NLS-1$
        if (Boolean.valueOf(urlRedirect)) {
            String redirectUrl = req.getContextPath() + "?mimeFile=" + file.getName(); //$NON-NLS-1$
            writer.write(redirectUrl);
        } else {
            writer.write(file.getAbsolutePath());
        }
    }
    writer.close();
}