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:de.htwg_konstanz.ebus.wholesaler.demo.workclasses.Upload.java

/**
 * Receives the XML File and generates an InputStream.
 *
 * @param request HttpServletRequest/*from   w ww  .java2  s  .co m*/
 * @return InputStream Stream of the uploaded file
 * @throws FileUploadException Exception Handling for File Upload
 * @throws IOException Exception Handling for IO Exceptions
 */
public InputStream upload(final HttpServletRequest request) throws FileUploadException, IOException {
    // Check Variable to check if it is a File Uploade
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        //Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        //Console Out Starting the Upload progress.
        System.out.println("\n - - - UPLOAD");

        // List of all uploaded Files
        List files = upload.parseRequest(request);

        // Returns the uploaded File
        Iterator iter = files.iterator();

        FileItem element = (FileItem) iter.next();
        String fileName = element.getName();
        String extension = FilenameUtils.getExtension(element.getName());

        // check if file extension is xml, when not then it will be aborted
        if (!extension.equals("xml")) {
            return null;
        }

        System.out.println("Extension:" + extension);

        System.out.println("\nFilename: " + fileName);

        // Escaping Special Chars
        fileName = fileName.replace('/', '\\');
        fileName = fileName.substring(fileName.lastIndexOf('\\') + 1);

        // Converts the File into an Input Strem
        InputStream is;
        is = element.getInputStream();

        return is;
    }
    return null;
}

From source file:de.knowwe.revisions.upload.UploadRevisionZip.java

@SuppressWarnings("unchecked")
@Override//from  w w w  .  ja va2  s  .c o  m
public void execute(UserActionContext context) throws IOException {

    HashMap<String, String> pages = new HashMap<>();
    List<FileItem> items = null;
    String zipname = null;
    try {
        items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(context.getRequest());
    } catch (FileUploadException e) {
        throw new IOException("error during processing upload", e);
    }

    for (FileItem item : items) {
        zipname = item.getName();
        InputStream filecontent = item.getInputStream();

        ZipInputStream zin = new ZipInputStream(filecontent);
        ZipEntry ze;

        while ((ze = zin.getNextEntry()) != null) {
            String name = ze.getName();
            if (!name.contains("/")) {
                // this is an article
                String title = Strings.decodeURL(name);
                title = title.substring(0, title.length() - 4);
                String content = IOUtils.toString(zin, "UTF-8");
                zin.closeEntry();
                pages.put(title, content);
            } else {
                // TODO: what to do here?
                // this is an attachment
                // String[] splittedName = name.split("/");
                // String title = Strings.decodeURL(splittedName[0]);
                // String filename = Strings.decodeURL(splittedName[1]);
                //
                // System.out.println("Attachment: " + name);
                // String content = IOUtils.toString(zin, "UTF-8");
                // Environment.getInstance().getWikiConnector().storeAttachment(title,
                // filename,
                // context.getUserName(), zin);
                zin.closeEntry();
            }
        }
        zin.close();
        filecontent.close();
    }
    if (zipname != null) {
        UploadedRevision rev = new UploadedRevision(context.getWeb(), pages, zipname);
        RevisionManager.getRM(context).setUploadedRevision(rev);
    }
    context.sendRedirect("../Wiki.jsp?page=" + context.getTitle());

}

From source file:com.groupon.odo.HttpUtilities.java

/**
 * Sets up the given {@link org.apache.commons.httpclient.methods.PostMethod} to send the same multipart POST data
 * as was sent in the given {@link HttpServletRequest}
 *
 * @param postMethodProxyRequest The {@link org.apache.commons.httpclient.methods.PostMethod} that we are configuring to send a
 *                               multipart POST request
 * @param httpServletRequest     The {@link HttpServletRequest} that contains the multipart
 *                               POST data to be sent via the {@link org.apache.commons.httpclient.methods.PostMethod}
 *///from w  w w . ja va  2 s  .  com
@SuppressWarnings("unchecked")
public static void handleMultipartPost(EntityEnclosingMethod postMethodProxyRequest,
        HttpServletRequest httpServletRequest, DiskFileItemFactory diskFileItemFactory)
        throws ServletException {

    // Create a new file upload handler
    ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
    // Parse the request
    try {
        // Get the multipart items as a list
        List<FileItem> listFileItems = (List<FileItem>) servletFileUpload.parseRequest(httpServletRequest);
        // Create a list to hold all of the parts
        List<Part> listParts = new ArrayList<Part>();
        // Iterate the multipart items list
        for (FileItem fileItemCurrent : listFileItems) {
            // If the current item is a form field, then create a string
            // part
            if (fileItemCurrent.isFormField()) {
                StringPart stringPart = new StringPart(fileItemCurrent.getFieldName(), // The field name
                        fileItemCurrent.getString() // The field value
                );
                // Add the part to the list
                listParts.add(stringPart);
            } else {
                // The item is a file upload, so we create a FilePart
                FilePart filePart = new FilePart(fileItemCurrent.getFieldName(), // The field name
                        new ByteArrayPartSource(fileItemCurrent.getName(), // The uploaded file name
                                fileItemCurrent.get() // The uploaded file contents
                        ));
                // Add the part to the list
                listParts.add(filePart);
            }
        }
        MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(
                listParts.toArray(new Part[listParts.size()]), postMethodProxyRequest.getParams());

        postMethodProxyRequest.setRequestEntity(multipartRequestEntity);

        // The current content-type header (received from the client) IS of
        // type "multipart/form-data", but the content-type header also
        // contains the chunk boundary string of the chunks. Currently, this
        // header is using the boundary of the client request, since we
        // blindly copied all headers from the client request to the proxy
        // request. However, we are creating a new request with a new chunk
        // boundary string, so it is necessary that we re-set the
        // content-type string to reflect the new chunk boundary string
        postMethodProxyRequest.setRequestHeader(STRING_CONTENT_TYPE_HEADER_NAME,
                multipartRequestEntity.getContentType());
    } catch (FileUploadException fileUploadException) {
        throw new ServletException(fileUploadException);
    }
}

From source file:by.creepid.jsf.fileupload.UploadedFile.java

public UploadedFile(FileItem fileItem, String longFileName, String shortFileName) {
    fileName = fileItem.getName();
    contentType = fileItem.getContentType();
    fileSize = fileItem.getSize();/*from   w w w .j  a  v a2s .  c o m*/
    fileContent = fileItem.getString();
    this.shortFileName = shortFileName;
    this.longFileName = longFileName;

    try {
        inputStream = fileItem.getInputStream();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.rampukar.controller.FileUploadHandler.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    //process only if its multipart content
    if (ServletFileUpload.isMultipartContent(request)) {
        try {/*from  w  ww.j  a  va2s  .  c o  m*/
            List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    String name = new File(item.getName()).getName();
                    item.write(new File(UPLOAD_DIRECTORY + File.separator + name));
                    out.print(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");
    }

    //        request.getRequestDispatcher("/result.jsp").forward(request, response);
}

From source file:com.tubes2.FileUploadHandler.FileUploadHandler.java

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

    //process only if its multipart content
    if (ServletFileUpload.isMultipartContent(request)) {
        try {/*w ww  .j av a2  s.co  m*/
            List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    String name = new File(item.getName()).getName();
                    item.write(new File(UPLOAD_DIRECTORY + 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");
    }

    request.getRequestDispatcher("/result.jsp").forward(request, response);

}

From source file:egovframework.com.utl.wed.filter.DefaultFileSaveManager.java

@Override
public String saveFile(FileItem fileItem, String imageBaseDir, String imageDomain) {
    String originalFileName = FilenameUtils.getName(fileItem.getName());
    String relUrl;//from w ww. j  av  a2  s  . c o  m
    // filename
    String subDir = File.separator + DirectoryPathManager
            .getDirectoryPathByDateType(DirectoryPathManager.DIR_DATE_TYPE.DATE_POLICY_YYYY_MM);
    String fileName = RandomStringUtils.randomAlphanumeric(20) + "."
            + StringUtils.lowerCase(StringUtils.substringAfterLast(originalFileName, "."));

    File newFile = new File(imageBaseDir + subDir + fileName);
    File fileToSave = DirectoryPathManager.getUniqueFile(newFile.getAbsoluteFile());

    try {
        FileUtils.writeByteArrayToFile(fileToSave, fileItem.get());
    } catch (IOException e) {
        e.printStackTrace();
    }

    String savedFileName = FilenameUtils.getName(fileToSave.getAbsolutePath());
    relUrl = StringUtils.replace(subDir, "\\", "/") + savedFileName;

    return imageDomain + relUrl;
}

From source file:com.sic.plugins.kpp.provider.KPPBaseProvisioningProfilesProvider.java

/**
 * Checks if a given file item is a mobile provision profile file.
 * @param item//from  w  ww.j a  v a2 s  .c om
 * @return true, if it is a mobile provision profile file.
 */
public boolean isMobileProvisionProfileFile(FileItem item) {
    return item.getName().endsWith(FILE_EXTENSION);
}

From source file:com.zlfun.framework.misc.UploadUtils.java

public static byte[] getFileBytes(HttpServletRequest request) {

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    // ???/*w  w w . java2s  .c  om*/
    // ??
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // ??

    //  ?? 
    factory.setSizeThreshold(1024 * 1024);

    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("UTF-8");
    try {
        // ?
        List<FileItem> list = (List<FileItem>) upload.parseRequest(request);

        for (FileItem item : list) {
            // ????
            String name = item.getFieldName();

            // ? ??  ?
            if (item.isFormField()) {
                // ? ?????? 
                String value = new String(item.getString().getBytes("iso-8859-1"), "utf-8");

                request.setAttribute(name, value);
            } // ? ??  
            else {
                /**
                 * ?? ??
                 */
                // ???
                String value = item.getName();
                // ?
                // ????
                value = java.net.URLDecoder.decode(value, "UTF-8");
                int start = value.lastIndexOf("\\");
                // ?  ??1 ???
                String filename = value.substring(start + 1);

                InputStream in = item.getInputStream();
                int length = 0;
                byte[] buf = new byte[1024];
                System.out.println("??" + item.getSize());
                // in.read(buf) ?? buf 
                while ((length = in.read(buf)) != -1) {
                    //  buf  ??  ??
                    out.write(buf, 0, length);
                }

                try {

                    if (in != null) {
                        in.close();
                    }

                } catch (IOException ex) {
                    Logger.getLogger(UploadUtils.class.getName()).log(Level.SEVERE, null, ex);
                }
                return out.toByteArray();

            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    } finally {
        try {
            out.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            Logger.getLogger(UploadUtils.class.getName()).log(Level.SEVERE, null, e);
        }
    }
    return null;

}

From source file:com.epam.wilma.webapp.config.servlet.stub.upload.MultiPartFileParser.java

/**
 * Parses a list of multipart files and sends them to {@link MultiPartFileProcessor}.
 * @param fields a list of multipart files that will be processed
 * @return with the processing status message or "No file uploaded" when the list is empty
 * @throws IOException was thrown file parsing failed
 *//*  www. j  a va2  s .com*/
public String parseMultiPartFiles(final List<FileItem> fields) throws IOException {
    String msg = "";
    Iterator<FileItem> it = fields.iterator();
    if (!fields.isEmpty() && it.hasNext()) {
        while (it.hasNext()) {
            FileItem fileItem = it.next();
            if (!fileItem.isFormField()) {
                String uploadedFileName = fileItem.getName();
                InputStream uploadedResource = fileItem.getInputStream();
                String contentType = fileItem.getContentType();
                String fieldName = fileItem.getFieldName();
                msg += multiPartFileProcessor.processUploadedFile(uploadedResource, contentType, fieldName,
                        uploadedFileName);
            }
        }
    } else {
        msg = "No file uploaded";
    }

    return msg;
}