Example usage for org.apache.commons.fileupload FileItem getInputStream

List of usage examples for org.apache.commons.fileupload FileItem getInputStream

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItem getInputStream.

Prototype

InputStream getInputStream() throws IOException;

Source Link

Document

Returns an java.io.InputStream InputStream that can be used to retrieve the contents of the file.

Usage

From source file:com.ephesoft.dcma.gwt.uploadbatch.server.UploadBatchImageServlet.java

private void uploadFile(HttpServletRequest req, HttpServletResponse resp, BatchSchemaService batchSchemaService,
        String currentBatchUploadFolderName) throws IOException {
    PrintWriter printWriter = resp.getWriter();
    File tempFile = null;/*  ww w  .j  a va 2s  .c  om*/
    InputStream instream = null;
    OutputStream out = null;
    String uploadBatchFolderPath = batchSchemaService.getUploadBatchFolder();
    String uploadFileName = "";
    if (ServletFileUpload.isMultipartContent(req)) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        uploadFileName = "";
        String uploadFilePath = "";
        List<FileItem> items;
        try {
            items = upload.parseRequest(req);

            for (FileItem item : items) {
                if (!item.isFormField()) { // && "uploadFile".equals(item.getFieldName())) {
                    uploadFileName = item.getName();
                    if (uploadFileName != null) {
                        uploadFileName = uploadFileName
                                .substring(uploadFileName.lastIndexOf(File.separator) + 1);
                    }
                    uploadFilePath = uploadBatchFolderPath + File.separator + currentBatchUploadFolderName
                            + File.separator + uploadFileName;

                    try {
                        instream = item.getInputStream();
                        tempFile = new File(uploadFilePath);

                        out = new FileOutputStream(tempFile);
                        byte buf[] = new byte[1024];
                        int len = instream.read(buf);
                        while (len > 0) {
                            out.write(buf, 0, len);
                            len = instream.read(buf);
                        }
                    } catch (FileNotFoundException e) {
                        LOG.error("Unable to create the upload folder." + e, e);
                        printWriter.write("Unable to create the upload folder.Please try again.");

                    } catch (IOException e) {
                        LOG.error("Unable to read the file." + e, e);
                        printWriter.write("Unable to read the file.Please try again.");
                    } finally {
                        if (out != null) {
                            out.close();
                        }
                        if (instream != null) {
                            instream.close();
                        }
                    }
                }
            }
        } catch (FileUploadException e) {
            LOG.error("Unable to read the form contents." + e, e);
            printWriter.write("Unable to read the form contents.Please try again.");
        }

    } else {
        LOG.error("Request contents type is not supported.");
        printWriter.write("Request contents type is not supported.");
    }
    printWriter.write("currentBatchUploadFolderName:" + currentBatchUploadFolderName);
    printWriter.append("|");

    printWriter.append("fileName:").append(uploadFileName);
    printWriter.append("|");

    printWriter.flush();
}

From source file:com.cloudbees.plugins.deployer.CloudbeesDeployWarTest.java

public void assertOnFileItems(String buildDescription) throws IOException {

    for (FileItem fileItem : cloudbeesServer.cloudbessServlet.items) {

        //archive check it's a war content

        //description check Jenkins BUILD_ID
        if (fileItem.getFieldName().equals("description")) {
            String description = fileItem.getString();
            assertEquals(buildDescription, description);
        } else if (fileItem.getFieldName().equals("api_key")) {
            assertEquals("Testing121212Testing", fileItem.getString());
        } else if (fileItem.getFieldName().equals("app_id")) {
            assertEquals("test-account/test-app", fileItem.getString());
        } else if (fileItem.getFieldName().equals("archive")) {
            assertOnArchive(fileItem.getInputStream());
        } else {//from  w  w w . j a  va2 s.  co  m
            System.out.println(" item " + fileItem);
        }

    }

}

From source file:com.ephesoft.gxt.systemconfig.server.ImportPluginUploadServlet.java

private void attachFile(HttpServletRequest req, HttpServletResponse resp, BatchSchemaService batchSchemaService)
        throws IOException {
    String errorMessageString = EMPTY_STRING;
    PrintWriter printWriter = resp.getWriter();
    File tempZipFile = null;//from  w  ww .  ja  v a 2s  .c om
    InputStream instream = null;
    OutputStream out = null;
    ZipInputStream zipInputStream = null;

    List<ZipEntry> zipEntries = null;
    if (ServletFileUpload.isMultipartContent(req)) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        String exportSerailizationFolderPath = EMPTY_STRING;

        try {
            Properties allProperties = ApplicationConfigProperties.getApplicationConfigProperties()
                    .getAllProperties(META_INF_APPLICATION_PROPERTIES);

            exportSerailizationFolderPath = allProperties.getProperty(PLUGIN_UPLOAD_PROPERTY_NAME);
        } catch (IOException e) {
        }
        File exportSerailizationFolder = new File(exportSerailizationFolderPath);
        if (!exportSerailizationFolder.exists()) {
            exportSerailizationFolder.mkdir();
        }

        List<FileItem> items;
        try {
            items = upload.parseRequest(req);
            for (FileItem item : items) {

                if (!item.isFormField()) {
                    zipFileName = item.getName();
                    if (zipFileName != null) {
                        zipFileName = zipFileName.substring(zipFileName.lastIndexOf(File.separator) + 1);
                    }
                    zipPathname = exportSerailizationFolderPath + File.separator + zipFileName;

                    try {
                        instream = item.getInputStream();
                        tempZipFile = new File(zipPathname);

                        if (tempZipFile.exists()) {
                            tempZipFile.delete();
                        }
                        out = new FileOutputStream(tempZipFile);
                        byte buf[] = new byte[1024];
                        int len;
                        while ((len = instream.read(buf)) > 0) {
                            out.write(buf, 0, len);
                        }
                    } catch (FileNotFoundException e) {
                        log.error("Unable to create the export folder." + e, e);
                        printWriter.write("Unable to create the export folder.Please try again.");

                    } catch (IOException e) {
                        log.error("Unable to read the file." + e, e);
                        printWriter.write("Unable to read the file.Please try again.");
                    } finally {
                        if (out != null) {
                            try {
                                out.close();
                            } catch (IOException ioe) {
                                log.info("Could not close stream for file." + tempZipFile);
                            }
                        }
                        if (instream != null) {
                            try {
                                instream.close();
                            } catch (IOException ioe) {
                                log.info("Could not close stream for file." + zipFileName);
                            }
                        }
                    }
                }
            }
        } catch (FileUploadException e) {
            log.error("Unable to read the form contents." + e, e);
            printWriter.write("Unable to read the form contents.Please try again.");
        }

        // Unnecessary code to unzip the attached file removed.

        zipInputStream = new ZipInputStream(new FileInputStream(zipPathname));

        zipEntries = new ArrayList<ZipEntry>();
        ZipEntry nextEntry = zipInputStream.getNextEntry();
        while (nextEntry != null) {
            zipEntries.add(nextEntry);
            nextEntry = zipInputStream.getNextEntry();
        }
        errorMessageString = processZipFileContents(zipEntries, zipPathname);

    } else {
        log.error("Request contents type is not supported.");
        printWriter.write("Request contents type is not supported.");
    }

    // Temp file is now not created.

    if (validZipContent) {
        String zipFileNameWithoutExtension = zipPathname.substring(0, zipPathname.lastIndexOf('.'));
        printWriter.write(SystemConfigConstants.PLUGIN_NAME + zipFileNameWithoutExtension);
        printWriter.append(RESULT_SEPERATOR);
        printWriter.append(SystemConfigConstants.JAR_FILE_PATH).append(jarFilePath);
        printWriter.append(RESULT_SEPERATOR);
        printWriter.append(SystemConfigConstants.XML_FILE_PATH).append(xmlFilePath);
        printWriter.append(RESULT_SEPERATOR);
        printWriter.flush();
    } else {
        printWriter.write("Error while importing.Please try again." + CAUSE + errorMessageString);
    }

}

From source file:eionet.gdem.utils.MultipartFileUpload.java

/**
 * Returns file as InputStream/*from  w ww  . j a  v  a2  s .  co m*/
 * @param fieldName Field name
 * @return InputStream
 * @throws GDEMException If an error occurs.
 * @throws IOException If an error occurs.
 */
public InputStream getFileAsInputStream(String fieldName) throws GDEMException, IOException {

    FileItem fileItem = getFileItem(fieldName);
    if (fileItem == null)
        throw new GDEMException("No files found!");

    if (fileItem.getSize() == 0)
        throw new GDEMException("File size is 0KB!"); // There is nothing to save, file size is 0

    return fileItem.getInputStream();
}

From source file:hk.hku.cecid.ebms.admin.listener.PartnershipPageletAdaptor.java

public Hashtable getHashtable(HttpServletRequest request) throws FileUploadException, IOException {
    Hashtable ht = new Hashtable();
    DiskFileUpload upload = new DiskFileUpload();
    List fileItems = upload.parseRequest(request);
    Iterator iter = fileItems.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();
        if (item.isFormField()) {
            ht.put(item.getFieldName(), item.getString());
        } else {/*from ww  w.j  a va  2 s. c om*/
            if (item.getName().equals("")) {
                //ht.put(item.getFieldName(), null);
            } else if (item.getSize() == 0) {
                //ht.put(item.getFieldName(), null);
            } else {
                ht.put(item.getFieldName(), item.getInputStream());
            }
        }
    }
    return ht;
}

From source file:com.ephesoft.gxt.uploadbatch.server.UploadBatchImageServlet.java

private void uploadFile(HttpServletRequest req, HttpServletResponse resp, BatchSchemaService batchSchemaService,
        String currentBatchUploadFolderName) throws IOException {

    PrintWriter printWriter = resp.getWriter();
    File tempFile = null;/*from w  ww . j av a 2s.  c  o m*/
    InputStream instream = null;
    OutputStream out = null;
    String uploadBatchFolderPath = batchSchemaService.getUploadBatchFolder();
    String uploadFileName = "";
    if (ServletFileUpload.isMultipartContent(req)) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        uploadFileName = "";
        String uploadFilePath = "";
        List<FileItem> items;
        try {
            items = upload.parseRequest(req);

            for (FileItem item : items) {
                if (!item.isFormField()) { // && "uploadFile".equals(item.getFieldName())) {
                    uploadFileName = item.getName();
                    if (uploadFileName != null) {
                        uploadFileName = uploadFileName
                                .substring(uploadFileName.lastIndexOf(File.separator) + 1);
                    }
                    uploadFilePath = uploadBatchFolderPath + File.separator + currentBatchUploadFolderName
                            + File.separator + uploadFileName;

                    try {
                        instream = item.getInputStream();
                        tempFile = new File(uploadFilePath);

                        out = new FileOutputStream(tempFile);
                        byte buf[] = new byte[1024];
                        int len;
                        while ((len = instream.read(buf)) > 0) {
                            out.write(buf, 0, len);
                        }
                    } catch (FileNotFoundException e) {
                        log.error("Unable to create the upload folder." + e, e);
                        printWriter.write("Unable to create the upload folder.Please try again.");
                        tempFile.delete();
                        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                "unable to upload. please see server logs for more details.");
                    } catch (IOException e) {
                        log.error("Unable to read the file." + e, e);
                        printWriter.write("Unable to read the file.Please try again.");
                        tempFile.delete();
                        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                "unable to upload. please see server logs for more details.");
                    } finally {
                        if (out != null) {
                            out.close();
                        }
                        if (instream != null) {
                            instream.close();
                        }
                    }
                }
            }
        } catch (FileUploadException e) {
            log.error("Unable to read the form contents." + e, e);
            printWriter.write("Unable to read the form contents.Please try again.");
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "unable to upload. please see server logs for more details.");
        }

    } else {
        log.error("Request contents type is not supported.");
        printWriter.write("Request contents type is not supported.");
    }
    printWriter.write("currentBatchUploadFolderName:" + currentBatchUploadFolderName);
    printWriter.append("|");

    printWriter.append("fileName:").append(uploadFileName);
    printWriter.append("|");

    printWriter.flush();
}

From source file:dk.netarkivet.harvester.webinterface.TrapCreateOrUpdateAction.java

@Override
protected void doAction(PageContext context, I18n i18n) {
    String name = null;//from w w w  .  j av a  2 s .  c om
    boolean isActive = true;
    String description = null;
    InputStream is = null;
    String id = null;
    String fileName = null;
    HttpServletRequest request = (HttpServletRequest) context.getRequest();
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    List<FileItem> items = null;
    try {
        items = upload.parseRequest(request);
    } catch (FileUploadException e) {
        HTMLUtils.forwardWithErrorMessage(context, i18n, e, "errormsg;crawlertrap.upload.error");
        throw new ForwardedToErrorPage("Error on multipart post", e);
    }
    for (FileItem item : items) {
        if (item.isFormField()) {
            if (item.getFieldName().equals(Constants.TRAP_NAME)) {
                name = item.getString();
            } else if (item.getFieldName().equals(Constants.TRAP_IS_ACTIVE)) {
                isActive = Boolean.parseBoolean(item.getString());
            } else if (item.getFieldName().equals(Constants.TRAP_DESCRIPTION)) {
                description = item.getString();
            } else if (item.getFieldName().equals(Constants.TRAP_ID)) {
                id = item.getString();
            }
        } else {
            try {
                fileName = item.getName();
                is = item.getInputStream();
            } catch (IOException e) {
                HTMLUtils.forwardWithErrorMessage(context, i18n, e, "errormsg;crawlertrap.upload.error");
                throw new ForwardedToErrorPage("Error on multipart post", e);
            }
        }
    }
    GlobalCrawlerTrapListDAO dao = GlobalCrawlerTrapListDBDAO.getInstance();
    if (id != null) { // update existing trap list
        int trapId = Integer.parseInt(id);
        GlobalCrawlerTrapList trap = dao.read(trapId);
        trap.setActive(isActive);
        trap.setDescription(description);
        trap.setName(name);
        if (fileName != null && !fileName.isEmpty()) {
            log.debug("Reading global crawler trap list from '" + fileName + "'");
            try {
                trap.setTrapsFromInputStream(is, name);
            } catch (ArgumentNotValid argumentNotValid) {
                HTMLUtils.forwardWithErrorMessage(context, i18n, "errormsg;crawlertrap.regexp.error");
                throw new ForwardedToErrorPage(argumentNotValid.getMessage());
            }
        }
        dao.update(trap);
    } else { // create new trap list
        log.debug("Reading global crawler trap list from '" + fileName + "'");
        GlobalCrawlerTrapList trap = new GlobalCrawlerTrapList(is, name, description, isActive);
        if (!dao.exists(name)) {
            dao.create(trap);
        } else {
            // crawlertrap named like this already exists.
            HTMLUtils.forwardWithErrorMessage(context, i18n, "errormsg;crawlertrap.0.exists.error", name);
            throw new ForwardedToErrorPage("Crawlertrap with name '" + name + "' exists already");
        }
    }
}

From source file:fr.aliasource.webmail.server.UploadAttachmentsImpl.java

@SuppressWarnings("rawtypes")
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    RequestContext ctx = new ServletRequestContext(req);
    String enc = ctx.getCharacterEncoding();
    logger.warn("received encoding is " + enc);
    if (enc == null) {
        enc = "utf-8";
    }/*from  www . j a v  a  2s  . com*/
    IAccount account = (IAccount) req.getSession().getAttribute("account");

    if (account == null) {
        resp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    DiskFileItemFactory factory = new DiskFileItemFactory(100 * 1024,
            new File(System.getProperty("java.io.tmpdir")));
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(20 * 1024 * 1024);

    List items = null;
    try {
        items = upload.parseRequest(req);
    } catch (FileUploadException e1) {
        logger.error("upload exception", e1);
        return;
    }

    // Process the uploaded items
    String id = null;
    Iterator iter = items.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();

        if (!item.isFormField()) {
            id = item.getFieldName();
            String fileName = removePathElementsFromFilename(item.getName());
            logger.warn("FileItem: " + item);
            long size = item.getSize();
            logger.warn("pushing upload of " + fileName + " to backend for " + account.getLogin() + "@"
                    + account.getDomain() + " size: " + size + ").");
            AttachmentMetadata meta = new AttachmentMetadata();
            meta.setFileName(fileName);
            meta.setSize(size);
            meta.setMime(item.getContentType());
            try {
                account.uploadAttachement(id, meta, item.getInputStream());
            } catch (Exception e) {
                logger.error("Cannot write uploaded file to disk");
            }
        }
    }
}

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

protected FileType parseMimeType(FileItem file) throws ApplicationException, IOException {
    FileType mime = FileType.forName(file.getContentType());

    if (mime.isUnknown()) {
        throw new ApplicationException().status(400)
                .devMessage(String.format("Invalid mime type detected '%s'", file.getContentType()))
                .code(ErrorMessageCode.BAD_UPLOAD_MIME);
    }/*from w  ww.ja  v  a 2 s .com*/

    Metadata mdata = new Metadata();
    InputStream in = file.getInputStream();
    String tikaMime = null;
    try {
        tikaMime = tika.detect(in, mdata);
    } finally {
        in.close();
    }

    log.debug(SERVICE, "Mime types resolved. HTTP Header: '{}' Tika: '{}'", file.getContentType(), tikaMime);
    if (!FileType.forName(tikaMime).isCovering(mime)) {
        throw new ApplicationException().status(400).devMessage(String
                .format("Mime type mismatch, expected: '%s' detected: '%s'", file.getContentType(), tikaMime))
                .code(ErrorMessageCode.BAD_UPLOAD_MIME);
    }
    return mime;
}

From source file:com.reachcall.pretty.http.ProxyServlet.java

@SuppressWarnings("unchecked")
private void doMultipart(HttpPost method, HttpServletRequest req)
        throws ServletException, FileUploadException, UnsupportedEncodingException, IOException {
    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
    diskFileItemFactory.setSizeThreshold(this.getMaxFileUploadSize());
    diskFileItemFactory.setRepository(TEMP_DIR);

    ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory);

    List<FileItem> fileItems = (List<FileItem>) upload.parseRequest(req);

    MultipartEntity entity = new MultipartEntity();

    for (FileItem fItem : fileItems) {
        if (fItem.isFormField()) {
            LOG.log(Level.INFO, "Form field {0}", fItem.getName());

            StringBody part = new StringBody(fItem.getFieldName());
            entity.addPart(fItem.getFieldName(), part);
        } else {//  w ww  . j ava 2s .  co  m
            LOG.log(Level.INFO, "File item {0}", fItem.getName());

            InputStreamBody file = new InputStreamBody(fItem.getInputStream(), fItem.getName(),
                    fItem.getContentType());
            entity.addPart(fItem.getFieldName(), file);
        }
    }

    method.setEntity(entity);
}