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:org.my.eaptest.UploadServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setContentType("text/html;charset=UTF-8");
    ServletOutputStream out = resp.getOutputStream();

    // Check that we have a file upload request.
    if (!ServletFileUpload.isMultipartContent(req)) {
        out.println(/*from   w  ww  . j a  v a 2s  .co  m*/
                "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">");
        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;
    }

    // Create a factory for disk-based file items.
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // Configure a repository (to ensure a secure temp location is used).
    ServletContext servletContext = this.getServletConfig().getServletContext();
    File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
    factory.setRepository(repository);
    // Maximum size that will be stored in memory.
    factory.setSizeThreshold(MAX_FILE_SIZE);
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);

    // Parse the request to get file items.
    try {
        List<FileItem> items = upload.parseRequest(req);

        out.println(
                "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<div style=\"text-align: left;\">");
        // we look for a filename item and/or file item with file content
        Iterator<FileItem> iter = items.iterator();
        String filename = null;
        String contents = null;
        boolean delete = false;
        while (iter.hasNext()) {
            FileItem item = iter.next();
            boolean isFormField = item.isFormField();
            String fieldName = item.getFieldName();
            if (isFormField && fieldName.equals("filename")) {
                String name = item.getString();
                if (name.length() > 0 || filename == null) {
                    filename = name;
                }
            } else if (isFormField && fieldName.equals("readonly")) {
                // means no filename or file provided
            } else if (isFormField && fieldName.equals("delete")) {
                // delete one or all fiels depending on whether filename is provided
                delete = true;
            } else if (!isFormField && fieldName.equals("file")) {
                contents = fromStream(item.getInputStream());
                contents = StringEscapeUtils.escapeHtml(contents);
                if (filename == null || filename.length() == 0) {
                    filename = item.getName();
                }
            } else {
                if (isFormField) {
                    out.print("<p><pre>Unexpected field name : ");
                    out.print(fieldName);
                    out.println("</pre>");
                } else {
                    String name = item.getName();
                    out.print("<p><pre>Unexpected file item : ");
                    out.print(name);
                    out.print(" for field ");
                    out.print(fieldName);
                    out.println("</pre>");
                }
                out.println("</body>");
                out.println("</html>");
                return;
            }
        }

        // if we don't have a filename then either list or delete all files in the hashtable

        if (filename == null) {
            if (delete) {
                filedata.clear();
                out.println("All files deleted!<br/>");
            } else {
                Set<String> keys = filedata.keySet();
                out.println("All files:<br/>");
                out.println("<pre>");
                if (keys.isEmpty()) {
                    out.println("No files found!");
                } else {
                    for (String key : keys) {
                        out.print(key);
                        FileSet set = filedata.get(key);
                        if (set != null) {
                            out.print(" ");
                            out.println(set.size());
                        } else {
                            out.println(" 0");
                        }
                    }
                }
                out.println("</pre>");
            }
            out.println("</body>");
            out.println("</html>");
            return;
        }
        // if we have a filename and no contents then we
        // retrieve the file contents from the hashmap
        // and maybe delete the file
        // if we have a filename and contents then we update
        // the hashmap -- delete should not be supplied in
        // this case

        boolean noUpdate = (contents == null);
        if (noUpdate) {
            if (delete) {
                FileSet set = filedata.remove(filename);
                contents = (set != null ? set.get() : null);
            } else {
                FileSet set = filedata.get(filename);
                contents = (set != null ? set.get() : null);
            }
        } else {
            FileSet set = new FileSet();
            FileSet old = filedata.putIfAbsent(filename, set);
            if (old != null) {
                set = old;
            }
            set.add(contents);
        }

        // now hand the contents back
        out.print("<pre>File: ");
        out.print(filename);
        boolean printContents = true;
        if (noUpdate) {
            if (contents == null) {
                out.println(" not found");
                printContents = false;
            } else if (delete) {
                out.print(" deleted");
            }
        } else {
            if (contents == null) {
                out.print(" added");
            } else {
                out.print(" updated");
            }
        }
        out.println("</pre><br/>");
        if (printContents) {
            out.println("<pre>");
            out.println(contents);
            out.println("</pre>");
        }
        out.println("</body>");
        out.println("</html>");
    } catch (FileUploadException fuEx) {
        log.error("Problem with process file upload:", fuEx);
    }
}

From source file:org.mycore.frontend.fileupload.MCRUploadViaFormServlet.java

private void handleUploadedFile(MCRUploadHandler handler, FileItem file) throws IOException, Exception {
    InputStream in = file.getInputStream();
    String path = MCRUploadHelper.getFileName(file.getName());

    MCRConfiguration config = MCRConfiguration.instance();
    if (config.getBoolean("MCR.FileUpload.DecompressZip", true)
            && path.toLowerCase(Locale.ROOT).endsWith(".zip"))
        handleZipFile(handler, in);//from   w w  w  .j  a v a  2s . co m
    else
        handleUploadedFile(handler, file.getSize(), path, in);
}

From source file:org.n52.geoar.codebase.resources.InfoResource.java

private Representation handleUpload() throws FileUploadException, Exception {
    // 1/ Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(1000240);//from  w w  w . jav  a2 s .  co m

    // 2/ Create a new file upload handler based on the Restlet FileUpload
    // extension that will
    // parse Restlet requests and generates FileItems.
    RestletFileUpload upload = new RestletFileUpload(factory);

    // 3/ Request is parsed by the handler which generates a list of
    // FileItems
    List<FileItem> items = upload.parseRequest(getRequest());

    // Process the uploaded item and the associated fields, then save file
    // on disk

    // get the form inputs
    FileItem dsFileItem = null;

    for (FileItem fi : items) {
        if (fi.getFieldName().equals(FORM_INPUT_FILE)) {
            dsFileItem = fi;
            break;
        }
    }

    if (dsFileItem.getName().isEmpty()) {
        return new StringRepresentation("Missing file!", MediaType.TEXT_PLAIN);
    }
    if (!FilenameUtils.getExtension(dsFileItem.getName()).equals(CodebaseProperties.APK_FILE_EXTENSION)) {
        return new StringRepresentation("Wrong filename extension", MediaType.TEXT_PLAIN);
    }

    PluginDescriptor pluginDescriptor = readPluginDescriptorFromPluginInputStream(dsFileItem.getInputStream());
    if (pluginDescriptor == null) {
        return new StringRepresentation(
                "The uploaded plugin has no descriptor (" + GEOAR_PLUGIN_XML_NAME + ")!", MediaType.TEXT_PLAIN);
    }
    if (pluginDescriptor.identifier == null) {
        return new StringRepresentation("The uploaded plugin has no identifier!", MediaType.TEXT_PLAIN);
    }

    log.debug("Plugin: {}, {}, {}, {}, {}", new Object[] { pluginDescriptor.identifier, pluginDescriptor.name,
            pluginDescriptor.description, pluginDescriptor.publisher, pluginDescriptor.version });

    // see if it already exists
    CodebaseDatabase db = CodebaseDatabase.getInstance();
    boolean databaseEntryExists = db.containsResource(pluginDescriptor.identifier);

    File pluginFile = new File(CodebaseProperties.getInstance().getApkPath(pluginDescriptor.identifier));
    File imageFile = new File(CodebaseProperties.getInstance().getImagePath(pluginDescriptor.identifier));
    if (pluginFile.exists()) {
        log.warn("Deleting apk file " + pluginFile.getName());
        if (!pluginFile.delete()) {
            log.error("Could not delete file " + pluginFile.getPath());
        }
    }
    if (imageFile.exists()) {
        log.warn("Deleting image file " + imageFile.getName());
        if (!imageFile.delete()) {
            log.error("Could not delete file " + imageFile.getPath());
        }
    }
    // write the file!
    dsFileItem.write(pluginFile);
    extractPluginImage(pluginFile, imageFile);

    if (databaseEntryExists) {
        db.updateResource(pluginDescriptor.identifier, pluginDescriptor.name, pluginDescriptor.description,
                pluginDescriptor.publisher, pluginDescriptor.version);
        return new StringRepresentation("Updated datasource (" + pluginDescriptor.identifier + ").",
                MediaType.TEXT_PLAIN);
    } else {
        db.addResource(pluginDescriptor.identifier, pluginDescriptor.name, pluginDescriptor.description,
                pluginDescriptor.publisher, pluginDescriptor.version);
        return new StringRepresentation("Uploaded datasource (" + pluginDescriptor.identifier + ").",
                MediaType.TEXT_PLAIN);
    }
}

From source file:org.ned.server.nedadminconsole.server.NedFileUploadServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    resp.setContentType("text/html");
    boolean isMultipart = ServletFileUpload.isMultipartContent(req);
    if (!isMultipart) {
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        resp.getWriter().print(NedServerResponses.ERROR_MULTIPART_CONTENT);
        resp.flushBuffer();//from  w  w  w  . j  a  v  a2 s .  co  m
        return; // send response
    }

    FileItemFactory factory = new DiskFileItemFactory();
    List<?> items = null;
    Iterator<?> iter = null;
    FileItem item = null;
    String name = null;
    String libraryId = null;
    String contentId = null;
    String file = null;
    String contentType = null;
    File uploadedFile = null;

    ServletFileUpload upload = new ServletFileUpload(factory);
    try {
        items = upload.parseRequest(req);
    } catch (FileUploadException ex) {
        ex.printStackTrace();
    }

    // now the downloading begins
    if (items == null) {
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        resp.getWriter().print(NedServerResponses.ERROR_BAD_REQUEST);
        resp.flushBuffer();
        return;
    }

    // first get only parameters
    iter = items.iterator();
    while (iter.hasNext()) {
        item = (FileItem) iter.next();

        if (item.getFieldName().equals("libId")) {
            libraryId = item.getString();
        } else if (item.getFieldName().equals("contentId")) {
            contentId = item.getString();
        } else if (item.getFieldName().equals("languageName")) {
            processUploadNewLanguage(items, resp);
            return;
        }
    }
    iter = items.iterator();
    while (iter.hasNext()) {
        item = (FileItem) iter.next();
        if (!item.isFormField()) {
            name = item.getName();
            int slashindex = name.lastIndexOf('\\');
            if (slashindex > -1) {
                file = name.substring(slashindex + 1, name.length());
            } else {
                file = name.substring(name.lastIndexOf('/') + 1, name.length());
            }

            contentType = getMediaType(name);
            if (contentType == null || contentType.isEmpty()) {
                resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
                resp.getWriter().print(NedServerResponses.ERROR_WRONG_FILE_TYPE);
                resp.flushBuffer();
                disconnectPostgres();
                return;
            }

            // FILE PATH CONSISTS OF
            // ROOT - TOMCAT_PATH\webapps\ROOT
            // BASEROOT - PASSED FROM CLIENT - librartId(signifies the catalogue instance)
            // nokiaecd\videos
            // FILENAME - GET FROM CHOSEN FILE

            String directory = createDirectory(libraryId);

            File fDir = new File(directory);
            fDir.getAbsolutePath();
            if (!fDir.exists()) {
                fDir.mkdirs();
            }

            file = createFilePath(directory, file);
            String uf = directory + file;
            uploadedFile = new File(uf);

            // //////////////////////////////////////////////
            InputStream uploadedStream = item.getInputStream();
            FileOutputStream fos = new FileOutputStream(uploadedFile);
            byte[] myarray = new byte[1024];
            int i = 0;
            while ((i = uploadedStream.read(myarray)) != -1) {
                fos.write(myarray, 0, i);
            }
            fos.flush();
            fos.close();
            uploadedStream.close();

            // update database
            try {
                getPosgresConnection().updateContentData(file, contentType, contentId);
            } catch (Exception ex) {
                // TODO delete file
                Logger.getLogger(NedFileUploadServlet.class.getSimpleName()).log(Level.SEVERE,
                        ex.getLocalizedMessage(), ex);
                resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                resp.getWriter().print(NedServerResponses.ERROR_DATABASE_UPDATE);
                resp.flushBuffer();
                disconnectPostgres();
                return;
            }
        }
    }

    resp.setStatus(HttpServletResponse.SC_OK);
    resp.getWriter().print(contentType);
    resp.flushBuffer();
    disconnectPostgres();
}

From source file:org.ned.server.nedadminconsole.server.NedFileUploadServlet.java

private void processUploadNewLanguage(List<?> items, HttpServletResponse resp) throws IOException {
    Iterator<?> iter = items.iterator();
    String languageName = null;//from  ww  w.j  ava2s.  c o m
    String languageLocale = null;
    String fileName;
    String finalFileName;
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();

        if (item.getFieldName().equals("languageName")) {
            languageName = item.getString();
        } else if (item.getFieldName().equals("languageLocale")) {
            languageLocale = item.getString();
        } else if (!item.isFormField()) {
            fileName = item.getName();
            int slashindex = fileName.lastIndexOf('\\');
            if (slashindex > -1) {
                finalFileName = fileName.substring(slashindex + 1, fileName.length());
            } else {
                finalFileName = fileName.substring(fileName.lastIndexOf('/') + 1, fileName.length());
            }

            // FILE PATH CONSISTS OF
            // ROOT - TOMCAT_PATH\webapps\ROOT
            // BASEROOT - Languages
            // FILENAME - GET FROM CHOSEN FILE

            String directory = createLanguageDir();

            File fDir = new File(directory);
            fDir.getAbsolutePath();
            if (!fDir.exists()) {
                fDir.mkdirs();
            }

            finalFileName = createFilePath(directory, finalFileName);
            String uf = directory + finalFileName;
            File uploadedFile = new File(uf);

            // //////////////////////////////////////////////
            InputStream uploadedStream = item.getInputStream();
            FileOutputStream fos = new FileOutputStream(uploadedFile);
            byte[] myarray = new byte[1024];
            int i = 0;
            while ((i = uploadedStream.read(myarray)) != -1) {
                fos.write(myarray, 0, i);
            }
            fos.flush();
            fos.close();
            uploadedStream.close();

            // update database
            try {
                if (languageName != null && languageLocale != null) {
                    getPosgresConnection().uploadNewLanguage(finalFileName, languageName, languageLocale);
                }
            } catch (Exception ex) {
                // TODO delete file
                Logger.getLogger(NedFileUploadServlet.class.getSimpleName()).log(Level.SEVERE,
                        ex.getLocalizedMessage(), ex);
                resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                resp.getWriter().print(NedServerResponses.ERROR_DATABASE_UPDATE);
                resp.flushBuffer();
                disconnectPostgres();
                return;
            }
        }
    }

}

From source file:org.netxilia.server.rest.WorkbookResource.java

@SuppressWarnings("unchecked")
@POST/*from ww  w .  ja va  2  s.  c om*/
@Path("/{workbook}/import")
@Produces({ MediaType.TEXT_HTML })
public ModelAndView<ImportSheetModel> importSheetsFromExcel(@PathParam("workbook") WorkbookId workbookId,
        @Context HttpServletRequest request) throws ImportException, IOException {

    long t1 = System.currentTimeMillis();
    List<SheetFullName> sheetNames = new ArrayList<SheetFullName>();
    StringBuilderProcessingConsole console = new StringBuilderProcessingConsole();

    if (ServletFileUpload.isMultipartContent(request)) {
        DiskFileItemFactory factory = new DiskFileItemFactory();

        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items = null;
        try {
            items = upload.parseRequest(request);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }

        String format = "json";

        if (items != null) {
            // check first form fields
            for (FileItem item : items) {
                if (!item.isFormField()) {
                    continue;
                }
                String name = item.getFieldName();
                String value = item.getString();
                if ("format".equals(name)) {
                    format = value;
                }
            }
            IImportService importService = "json".equals(format) ? jsonImportService : excelImportService;
            for (FileItem item : items) {
                if (!item.isFormField() && item.getSize() > 0) {
                    sheetNames.addAll(importService.importSheets(getWorkbookProcessor(), workbookId,
                            item.getInputStream(), console));
                }
            }
        }
    }
    long t2 = System.currentTimeMillis();
    return new ModelAndView<ImportSheetModel>(
            new ImportSheetModel(sheetNames, console.getContent().toString(), (t2 - t1)),
            "/WEB-INF/jsp/workbook/importSheet.jsp");
}

From source file:org.niord.core.batch.AbstractBatchableRestService.java

/**
 * Starts the batch job on the given file
 *
 * @param batchJobName the batch job name
 * @param fileItem the file item/*from  ww w .jav a2  s . c  o  m*/
 * @param params the non-file form parameters
 * @param txt a log of the import
 */
private void startBatchJob(String batchJobName, FileItem fileItem, Map<String, Object> params,
        StringBuilder txt) throws Exception {
    batchService.startBatchJobWithDataFile(batchJobName, fileItem.getInputStream(), fileItem.getName(), params);

    String message = "Started batch job '" + batchJobName + "' with file " + fileItem.getName();
    log.info(message);
    txt.append(message);
}

From source file:org.niord.core.repo.RepositoryService.java

/**
 * Handles upload of files/*from   w  w w  .  ja v a  2s. co m*/
 *
 * @param path the folder to upload to
 * @param request the request
 */
@POST
@javax.ws.rs.Path("/upload/{folder:.+}")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces("application/json;charset=UTF-8")
@RolesAllowed(Roles.EDITOR)
public List<String> uploadFile(@PathParam("folder") String path, @Context HttpServletRequest request)
        throws FileUploadException, IOException {

    Path folder = repoRoot.resolve(path);

    if (Files.exists(folder) && !Files.isDirectory(folder)) {
        log.warn("Failed streaming file to folder: " + folder);
        throw new WebApplicationException("Invalid upload folder: " + path, 403);

    } else if (Files.notExists(folder)) {
        try {
            Files.createDirectories(folder);
        } catch (IOException e) {
            log.error("Error creating repository folder " + folder, e);
            throw new WebApplicationException("Invalid upload folder: " + path, 403);
        }
    }

    List<String> result = new ArrayList<>();
    List<FileItem> items = parseFileUploadRequest(request);

    for (FileItem item : items) {
        if (!item.isFormField()) {
            // Argh - IE includes the path in the item.getName()!
            String fileName = Paths.get(item.getName()).getFileName().toString();
            File destFile = getUniqueFile(folder, fileName).toFile();
            log.info("File " + fileName + " is uploaded to " + destFile);
            try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(destFile))) {
                InputStream in = new BufferedInputStream(item.getInputStream());
                byte[] buffer = new byte[1024];
                int len = in.read(buffer);
                while (len != -1) {
                    out.write(buffer, 0, len);
                    len = in.read(buffer);
                }
                out.flush();
            }

            // Return the repo-relative path as a result
            result.add(Paths.get(path, destFile.getName()).toString());
        }
    }

    return result;
}

From source file:org.niord.importer.aton.AtonImportRestService.java

/**
 * Imports an uploaded AtoN Excel file//w  ww.  j ava  2 s . co  m
 *
 * @param request the servlet request
 * @return a status
 */
@POST
@Path("/upload-xls")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces("text/plain")
@RolesAllowed("admin")
public String importXls(@Context HttpServletRequest request) throws Exception {

    FileItemFactory factory = RepositoryService.newDiskFileItemFactory(servletContext);
    ServletFileUpload upload = new ServletFileUpload(factory);
    List<FileItem> items = upload.parseRequest(request);

    StringBuilder txt = new StringBuilder();

    for (FileItem item : items) {
        if (!item.isFormField()) {
            String name = item.getName().toLowerCase();

            // AtoN Import
            if (name.startsWith("afmmyndighed_table") && name.endsWith(".xls")) {
                importAtoN(item.getInputStream(), item.getName(), txt);

            } else if (name.startsWith("fyr") && name.endsWith(".xls")) {
                importLights(item.getInputStream(), item.getName(), txt);

            } else if (name.startsWith("ais") && name.endsWith(".xls")) {
                importAis(item.getInputStream(), item.getName(), txt);

            } else if (name.startsWith("dgps") && name.endsWith(".xls")) {
                importDgps(item.getInputStream(), item.getName(), txt);

            } else if (name.startsWith("racon") && name.endsWith(".xls")) {
                importRacons(item.getInputStream(), item.getName(), txt);
            }
        }
    }

    return txt.toString();
}

From source file:org.niord.web.map.MessageMapImageRestService.java

/**
 * Called to upload a custom message map image via a multipart form-data request
 *
 * @param request the servlet request//  ww  w  . ja  v  a 2s.  c  o m
 * @return a status
 */
@POST
@javax.ws.rs.Path("/{folder:.+}")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces("text/plain")
@RolesAllowed(Roles.EDITOR)
public String uploadMessageMapImage(@PathParam("folder") String path, @Context HttpServletRequest request)
        throws Exception {

    // Validate that the path is a temporary repository folder path
    Path folder = repositoryService.validateTempRepoPath(path);

    List<FileItem> items = repositoryService.parseFileUploadRequest(request);

    // Get hold of the first uploaded image
    FileItem imageItem = items.stream().filter(item -> !item.isFormField()).findFirst().orElse(null);

    if (imageItem == null) {
        throw new WebApplicationException(400);
    }
    // Construct the file path for the message
    String imageName = String.format("custom_thumb_%d.png", messageMapImageGenerator.getMapImageSize());
    Path imageRepoPath = folder.resolve(imageName);

    try {
        byte[] data = IOUtils.toByteArray(imageItem.getInputStream());
        if (messageMapImageGenerator.generateMessageMapImage(data, imageRepoPath)) {
            log.info("Generated image thumbnail from uploaded image");
        } else {
            log.error("Failed generating image thumbnail from uploaded image");
        }
    } catch (IOException e) {
        log.error("Error generating image thumbnail from uploaded image:\nError: ", e);
    }

    return path + "/" + imageName;
}