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:de.fhg.fokus.openride.services.profile.ProfileService.java

@POST
@Path("picture/")
@Produces("text/json")
public Response postPicture(@Context HttpServletRequest con, @PathParam("username") String username) {

    System.out.println("postPicture start");

    boolean success = false;

    //String profilePicturesPath = "C:\\OpenRide\\pictures\\profile";
    String profilePicturesPath = "../OpenRideWeb/img/profile/default";

    //TODO/*from   www  . j  a v a  2 s  .  com*/
    //String imagePath = getServletConfig().getInitParameter("imagePath");

    // FIXME: The following try/catch may be removed for production deployments:
    /*try {
    if (java.net.InetAddress.getLocalHost().getHostName().equals("elan-tku-r2032.fokus.fraunhofer.de")) {
        profilePicturesPath = "/mnt/windows/OpenRide/pictures/profile";
    }
    else if (java.net.InetAddress.getLocalHost().getHostName().equals("robusta2.fokus.fraunhofer.de")) {
        profilePicturesPath = "/usr/lib/openride/pictures/profile";
    }
    } catch (UnknownHostException ex) {
    }*/

    int picSize = 125;
    int picThumbSize = 60;

    // check if remote user == {username} in path param
    if (!username.equals(con.getRemoteUser())) {
        return Response.status(Response.Status.FORBIDDEN).build();
    }

    if (ServletFileUpload.isMultipartContent(con)) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items = null;
        try {
            items = upload.parseRequest(con);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        if (items != null) {
            Iterator<FileItem> iter = items.iterator();

            CustomerEntity c = customerControllerBean.getCustomerByNickname(username);
            String uploadedFileName = c.getCustNickname() + "_" + c.getCustId();

            while (iter.hasNext()) {
                FileItem item = iter.next();
                if (!item.isFormField() && item.getSize() > 0) {

                    try {
                        BufferedImage uploadedPicture = ImageIO.read(item.getInputStream());

                        int newWidth, newHeight;
                        int xPos, yPos;
                        float ratio = (float) uploadedPicture.getHeight() / (float) uploadedPicture.getWidth();

                        // Resize for "large" size
                        if (uploadedPicture.getWidth() > uploadedPicture.getHeight()) {
                            newWidth = picSize;
                            newHeight = Math.round(newWidth * ratio);
                        } else {
                            newHeight = picSize;
                            newWidth = Math.round(newHeight / ratio);
                        }

                        //System.out.println("new dimensions "+newWidth+"x"+newHeight);

                        Image resizedPicture = uploadedPicture.getScaledInstance(newWidth, newHeight,
                                Image.SCALE_SMOOTH);

                        xPos = Math.round((picSize - newWidth) / 2);
                        yPos = Math.round((picSize - newHeight) / 2);
                        BufferedImage bim = new BufferedImage(picSize, picSize, BufferedImage.TYPE_INT_RGB);
                        bim.createGraphics().setColor(Color.white);
                        bim.createGraphics().fillRect(0, 0, picSize, picSize);
                        bim.createGraphics().drawImage(resizedPicture, xPos, yPos, null);

                        File outputPicture = new File(profilePicturesPath, uploadedFileName + ".jpg");

                        ImageIO.write(bim, "jpg", outputPicture);

                        // Resize again for "thumb" size
                        if (uploadedPicture.getWidth() > uploadedPicture.getHeight()) {
                            newWidth = picThumbSize;
                            newHeight = Math.round(newWidth * ratio);
                        } else {
                            newHeight = picThumbSize;
                            newWidth = Math.round(newHeight / ratio);
                        }

                        //System.out.println("new dimensions "+newWidth+"x"+newHeight);

                        resizedPicture = uploadedPicture.getScaledInstance(newWidth, newHeight,
                                Image.SCALE_SMOOTH);

                        xPos = Math.round((picThumbSize - newWidth) / 2);
                        yPos = Math.round((picThumbSize - newHeight) / 2);
                        bim = new BufferedImage(picThumbSize, picThumbSize, BufferedImage.TYPE_INT_RGB);
                        bim.createGraphics().setColor(Color.white);
                        bim.createGraphics().fillRect(0, 0, picThumbSize, picThumbSize);
                        bim.createGraphics().drawImage(resizedPicture, xPos, yPos, null);

                        outputPicture = new File(profilePicturesPath, uploadedFileName + "_thumb.jpg");

                        ImageIO.write(bim, "jpg", outputPicture);

                    } catch (Exception e) {
                        e.printStackTrace();
                        System.out.println("File upload / resize unsuccessful.");
                    }
                    success = true;
                }
            }
        }
    }

    if (success) {

        // TODO: Perhaps introduce a redirection target as a parameter to the putProfile method and redirect to that URL (code 301/302) instead of just doing nothing.
        return null;

        /*
        try {
        String referer = con.getHeader("HTTP_REFERER");
        System.out.println("putPicture: Referer: " + referer);
        if (referer != null)
        return Response.status(Response.Status.SEE_OTHER).contentLocation(new URI(referer)).build();
        else
        return Response.ok().build();
        } catch (URISyntaxException ex) {
        Logger.getLogger(ProfileService.class.getName()).log(Level.SEVERE, null, ex);
        return Response.status(Response.Status.BAD_REQUEST).build();
        }
         */
    } else {
        return Response.status(Response.Status.BAD_REQUEST).build();
    }
}

From source file:com.ephesoft.gxt.foldermanager.server.UploadDownloadFilesServlet.java

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

    PrintWriter printWriter = resp.getWriter();
    File tempFile = null;/*from   w  ww. j a  va  2  s. c o m*/
    InputStream instream = null;
    OutputStream out = null;
    String uploadFileName = "";
    try {
        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()) {
                        uploadFileName = item.getName();
                        if (uploadFileName != null) {
                            uploadFileName = uploadFileName
                                    .substring(uploadFileName.lastIndexOf(File.separator) + 1);
                        }
                        uploadFilePath = 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) {
                            printWriter.write("Unable to create the upload folder.Please try again.");

                        } catch (IOException 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) {
                printWriter.write("Unable to read the form contents.Please try again.");
            }

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

        printWriter.append("fileName:").append(uploadFileName);
        printWriter.append("|");
    } finally {
        printWriter.flush();
        printWriter.close();
    }
}

From source file:com.ikon.servlet.WorkflowRegisterServlet.java

@SuppressWarnings("unchecked")
private String handleRequest(HttpServletRequest request) throws FileUploadException, IOException, Exception {
    log.debug("handleRequest({})", request);

    if (ServletFileUpload.isMultipartContent(request)) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items = upload.parseRequest(request);

        if (items.isEmpty()) {
            String msg = "No process file in the request";
            log.warn(msg);//  w  w  w  .  j a  v  a  2  s  .co m
            return msg;
        } else {
            FileItem fileItem = (FileItem) items.get(0);

            if (fileItem.getContentType().indexOf("application/x-zip-compressed") == -1) {
                String msg = "Not a process archive";
                log.warn(msg);
                throw new Exception(msg);
            } else {
                log.info("Deploying process archive: {}", fileItem.getName());
                JbpmContext jbpmContext = JBPMUtils.getConfig().createJbpmContext();
                InputStream isForms = null;
                ZipInputStream zis = null;

                try {
                    zis = new ZipInputStream(fileItem.getInputStream());
                    ProcessDefinition processDefinition = ProcessDefinition.parseParZipInputStream(zis);

                    // Check XML form definition
                    FileDefinition fileDef = processDefinition.getFileDefinition();
                    isForms = fileDef.getInputStream("forms.xml");
                    FormUtils.parseWorkflowForms(isForms);

                    log.debug("Created a processdefinition: {}", processDefinition.getName());
                    jbpmContext.deployProcessDefinition(processDefinition);
                    return "Process " + processDefinition.getName() + " deployed successfully";
                } finally {
                    IOUtils.closeQuietly(isForms);
                    IOUtils.closeQuietly(zis);
                    jbpmContext.close();
                }
            }
        }
    } else {
        log.warn("Not a multipart request");
        return "Not a multipart request";
    }
}

From source file:com.artofsolving.jodconverter.web.DocumentConverterServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    ApplicationContext applicationContext = WebApplicationContextUtils
            .getRequiredWebApplicationContext(getServletContext());
    ServletFileUpload fileUpload = (ServletFileUpload) applicationContext.getBean("fileUpload");
    DocumentConverter converter = (DocumentConverter) applicationContext.getBean("documentConverter");
    DocumentFormatRegistry registry = (DocumentFormatRegistry) applicationContext
            .getBean("documentFormatRegistry");

    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new IllegalArgumentException("request is not multipart");
    }/*from   w  w  w.j ava  2 s .  co  m*/

    // determine output format based on the request uri
    String outputExtension = FilenameUtils.getExtension(request.getRequestURI());
    DocumentFormat outputFormat = registry.getFormatByFileExtension(outputExtension);
    if (outputFormat == null) {
        throw new IllegalArgumentException("invalid outputFormat: " + outputExtension);
    }

    FileItem inputFileUpload = getInputFileUpload(request, fileUpload);
    if (inputFileUpload == null) {
        throw new IllegalArgumentException("inputDocument is null");
    }
    String inputExtension = FilenameUtils.getExtension(inputFileUpload.getName());
    DocumentFormat inputFormat = registry.getFormatByFileExtension(inputExtension);

    response.setContentType(outputFormat.getMimeType());
    String fileName = FilenameUtils.getBaseName(inputFileUpload.getName()) + "."
            + outputFormat.getFileExtension();
    response.setHeader("Content-Disposition", "inline; filename=" + fileName);
    //response.setContentLength(???);

    converter.convert(inputFileUpload.getInputStream(), inputFormat, response.getOutputStream(), outputFormat);
}

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  w w  . j a  v a 2  s  . com
 * @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:au.org.ala.layers.web.ShapesService.java

@RequestMapping(value = "/shape/upload/shp", method = RequestMethod.POST)
@ResponseBody/* www.  j  ava2 s .c o  m*/
public Map<Object, Object> uploadShapeFile(HttpServletRequest req, HttpServletResponse resp,
        @RequestParam(value = "user_id", required = false) String userId,
        @RequestParam(value = "api_key", required = false) String apiKey) throws Exception {
    // Use linked hash map to maintain key ordering
    Map<Object, Object> retMap = new LinkedHashMap<Object, Object>();

    File tmpZipFile = File.createTempFile("shpUpload", ".zip");

    if (!ServletFileUpload.isMultipartContent(req)) {
        String jsonRequestBody = IOUtils.toString(req.getReader());

        JSONRequestBodyParser reqBodyParser = new JSONRequestBodyParser();
        reqBodyParser.addParameter("user_id", String.class, false);
        reqBodyParser.addParameter("shp_file_url", String.class, false);
        reqBodyParser.addParameter("api_key", String.class, false);

        if (reqBodyParser.parseJSON(jsonRequestBody)) {

            String shpFileUrl = (String) reqBodyParser.getParsedValue("shp_file_url");
            userId = (String) reqBodyParser.getParsedValue("user_id");
            apiKey = (String) reqBodyParser.getParsedValue("api_key");

            if (!checkAPIKey(apiKey, userId)) {
                retMap.put("error", "Invalid user ID or API key");
                return retMap;
            }

            // Use shape file url from json body
            InputStream is = null;
            OutputStream os = null;
            try {
                is = new URL(shpFileUrl).openStream();
                os = new FileOutputStream(tmpZipFile);
                IOUtils.copy(is, os);
                retMap.putAll(handleZippedShapeFile(tmpZipFile));
                os.flush();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (Exception e) {
                        logger.error(e.getMessage(), e);
                    }
                }
                if (os != null) {
                    try {
                        os.close();
                    } catch (Exception e) {
                        logger.error(e.getMessage(), e);
                    }
                }
            }

        } else {
            retMap.put("error", StringUtils.join(reqBodyParser.getErrorMessages(), ","));
        }

    } else {
        if (false && !checkAPIKey(apiKey, userId)) {
            retMap.put("error", "Invalid user ID or API key");
            return retMap;
        }

        // Create a factory for disk-based file items. File size limit is
        // 50MB
        // Configure a repository (to ensure a secure temp location is used)
        File repository = new File(System.getProperty("java.io.tmpdir"));
        DiskFileItemFactory factory = new DiskFileItemFactory(1024 * 1024 * 50, repository);

        factory.setRepository(repository);

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

        // Parse the request
        List<FileItem> items = upload.parseRequest(req);

        if (items.size() == 1) {
            FileItem fileItem = items.get(0);
            IOUtils.copy(fileItem.getInputStream(), new FileOutputStream(tmpZipFile));
            retMap.putAll(handleZippedShapeFile(tmpZipFile));
        } else {
            retMap.put("error",
                    "Multiple files sent in request. A single zipped shape file should be supplied.");
        }
    }

    return retMap;
}

From source file:edu.umd.cs.submitServer.filters.RegisterStudentsFilter.java

@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) resp;
    if (!request.getMethod().equals("POST")) {
        throw new ServletException("Only POST accepted");
    }/*ww w . j a va  2  s .  com*/
    Connection conn = null;
    BufferedReader reader = null;
    FileItem fileItem = null;
    TreeSet<StudentRegistration> registeredStudents = new TreeSet<StudentRegistration>();
    List<String> errors = new ArrayList<String>();
    try {
        conn = getConnection();

        // MultipartRequestFilter is required
        MultipartRequest multipartRequest = (MultipartRequest) request.getAttribute(MULTIPART_REQUEST);

        Course course = (Course) request.getAttribute("course");

        // open the uploaded file
        fileItem = multipartRequest.getFileItem();
        reader = new BufferedReader(new InputStreamReader(fileItem.getInputStream()));

        int lineNumber = 1;

        while (true) {
            String line = reader.readLine();
            if (line == null)
                break;
            lineNumber++;

            // hard-coded skip of first two lines for Maryland-specific
            // format
            if (line.startsWith("Last,First,UID,section,ClassAcct,DirectoryID"))
                continue;
            if (line.startsWith(",,,,,")) {
                if (line.equals(",,,,,"))
                    continue;
                String ldap = line.substring(5);
                Student student = Student.lookupByLoginName(ldap, conn);
                if (student != null) {
                    StudentRegistration sr = StudentForUpload.registerStudent(course, student, "", ldap, null,
                            conn);
                    registeredStudents.add(sr);
                } else
                    errors.add("Did not find " + ldap);

                continue;

            }
            if (line.startsWith("#"))
                continue;

            // skip blank lines
            if (line.trim().equals(""))
                continue;

            try {
                StudentForUpload s = new StudentForUpload(line, delimiter);

                Student student = s.lookupOrInsert(conn);
                StudentRegistration sr = StudentForUpload.registerStudent(course, student, s.section,
                        s.classAccount, null, conn);
                registeredStudents.add(sr);

            } catch (IllegalStateException e) {
                errors.add(e.getMessage());
                ServletExceptionFilter.logError(conn, ServerError.Kind.EXCEPTION, request,
                        "error while registering " + line, null, e);

            } catch (Exception e1) {
                errors.add("Problem processing line: '" + line + "' at line number: " + lineNumber);
                ServletExceptionFilter.logError(conn, ServerError.Kind.EXCEPTION, request,
                        "error while registering " + line, null, e1);
            }
        }
    } catch (SQLException e) {
        throw new ServletException(e);
    } finally {
        releaseConnection(conn);
        if (reader != null)
            reader.close();
        if (fileItem != null)
            fileItem.delete();
    }
    request.setAttribute("registeredStudents", registeredStudents);
    request.setAttribute("errors", errors);
    chain.doFilter(request, response);
}

From source file:com.cloudbees.plugins.deployer.JobConfigBuilderTest.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")) {
            CloudbeesDeployWarTest.assertOnArchive(fileItem.getInputStream());
        } else {//from  ww w.j a  va  2 s  .c  o m
            System.out.println(" item " + fileItem);
        }

    }

}

From source file:com.bibisco.filters.FileFilter.java

/**
 * Example of how to get useful things with the uploaded file structure.
  * Generally speaking, this method should be overrided by framework's users.
 * //from  ww w  . j  a va2 s  .co m
 * <p>Here we demostrate how to extract useful infos 
 * (<code>name, value, isInMemory, size, etc) </code>)
 * plus how to deal with memory- or disk-persisted cases.
 * 
 * <li><p>We pass the whole <code>FileItem</code> structure
 * to the next <code>jsp</code> page, which gains the ability to extract 
 * infos as well: via Request, under name: "file-" + fieldname
 * 
 * <li><p>The file content can be retrieved here or later, <code>FileItem</code>
 * object can use its data-getters in <code>.jsp</code>s! 
 * <p>In this code, we retrieve file content and pass it in Request 
 * for next uses under the a general format of 
 * array of bytes (<code>byte []</code>);  with name equal to "file-" + fieldname.  
 *  
 * @param pItem
 * @throws IOException
 */
protected void processUploadedFile(FileItem pItem, ServletRequest pRequest) throws IOException {
    String name = pItem.getFieldName();
    boolean isInMemory = pItem.isInMemory();
    pRequest.setAttribute("file-" + name, pItem);

    if (isInMemory) {
        mLog.debug("the file ", name, " is in memory under the request attribute file-content-", name);
        byte[] data = pItem.get();
        pRequest.setAttribute("file-content-" + name, data);
    } else {
        mLog.debug("the file ", name, " is in the file system and under the request attribute file-content-",
                name);
        InputStream uploadedStream = pItem.getInputStream();
        byte[] data = (new StreamTokenizer(new BufferedReader(new InputStreamReader(uploadedStream))))
                .toString().getBytes();
        uploadedStream.close();
        pRequest.setAttribute("file-content-" + name, data);
    }
}

From source file:mercury.Controller.java

public void putAllRequestParametersInAttributes(HttpServletRequest request) {
    ArrayList fileBeanList = new ArrayList();
    HashMap<String, String> ht = new HashMap<String, String>();

    String fieldName = null;/*from   w w  w. ja v a 2 s  .c om*/
    String fieldValue = null;
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (isMultipart) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        java.util.List items = null;
        try {
            items = upload.parseRequest(request);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        Iterator iter = items.iterator();

        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            if (item.isFormField()) {
                fieldName = item.getFieldName();
                fieldValue = item.getString();
                ht.put(fieldName, fieldValue);
            } else if (!item.isFormField()) {
                UploadedFileBean bean = new UploadedFileBean();
                bean.setFileItem(item);
                bean.setContentType(item.getContentType());
                bean.setFileName(item.getName());
                try {
                    bean.setInputStream(item.getInputStream());
                } catch (Exception e) {
                    System.out.println("=== Erro: " + e);
                }
                bean.setIsInMemory(item.isInMemory());
                bean.setSize(item.getSize());
                fileBeanList.add(bean);
                request.getSession().setAttribute("UPLOADED_FILE", bean);
            }
        }
    } else if (!isMultipart) {
        Enumeration<String> en = request.getParameterNames();

        String name = null;
        String value = null;
        while (en.hasMoreElements()) {
            name = en.nextElement();
            value = request.getParameter(name);
            ht.put(name, value);
        }
    }

    request.setAttribute("REQUEST_PARAMETERS", ht);
}