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:edu.byui.fb.AddImage.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request// w  ww .  j  ava2s .  co  m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // Get the DataBaseHandler
    DataBaseHandler dbh = DataBaseHandler.getInstance();

    // Get information about the user currently logged in
    boolean logged = (boolean) request.getSession().getAttribute("logged");
    String username = (String) request.getSession().getAttribute("username");
    User user = dbh.getUser(username);

    // Are we currently logged in
    if (username != null && user != null && logged) {
        // Check to make sure the request is multipart
        if (ServletFileUpload.isMultipartContent(request)) {
            try {
                // Parse the request into FileItems
                List<FileItem> multipart = new ServletFileUpload(new DiskFileItemFactory())
                        .parseRequest(request);
                String title = "";
                InputStream imageInputStream = null;

                // Loop through each item
                for (FileItem item : multipart) {
                    // Are we dealing with a file or something different
                    if (!item.isFormField()) {
                        if (item.getFieldName().equals("image")) {
                            imageInputStream = item.getInputStream();
                        }
                    } else if (item.isFormField()) {
                        if (item.getFieldName().equals("title")) {
                            title = item.getString();
                        }
                    }
                }

                // Was there a title? If not, give a fake title
                if (title.equals("")) {
                    title = "No title";
                }

                // Set up the image and add to the DataBase.
                Image image = new Image(title, imageInputStream);
                dbh.addImage(image, user);
                request.setAttribute("imageAdded", true);
            } catch (FileUploadException ex) {
                Logger.getLogger(AddImage.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    } else {
        // Was there an error?
        request.setAttribute("addedError", true);
    }

    // Go to admin.jsp
    request.getRequestDispatcher("LoadImages?dest=admin.jsp").forward(request, response);
}

From source file:com.pureinfo.tgirls.servlet.TestServlet.java

private int[] getimgSize(FileItem _fileItem) {
    try {/*from   w  w  w .j a  va2s.com*/
        logger.debug("to calc img width and height.");

        Image image = ImageIO.read(_fileItem.getInputStream());
        int[] s = new int[2];
        s[0] = image.getWidth(null);
        s[1] = image.getHeight(null);

        logger.debug("width[" + s[0] + "] height[" + s[1] + "]");

        return s;
    } catch (Exception e) {
        logger.error("error when calc image size.", e);
        return new int[] { -1, -1 };
    }
}

From source file:com.osbitools.ws.shared.prj.web.ExFileMgrWsSrvServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {/*from  w ww . j a va2s .c  o m*/
        super.doPost(req, resp);
    } catch (ServletException e) {
        if (e.getCause().getClass().equals(WsSrvException.class)) {
            // Authentication failed
            checkSendError(req, resp, (WsSrvException) e.getCause());
            return;
        } else {
            throw e;
        }
    }

    // Get File name and extension
    EntityUtils eut = getEntityUtils(req);
    String name = req.getParameter(FNAME);
    String dname = req.getParameter(DNAME);

    HashSet<String> extl;
    try {
        extl = getExtListByDirName(eut, dname);
    } catch (WsSrvException e) {
        checkSendError(req, resp, e);
        return;
    }

    // Check if rename required
    String rename = req.getParameter("rename_to");
    if (rename != null) {
        if (rename.equals("")) {
            //-- 235
            checkSendError(req, resp, 235, "Empty parameter rename_to");
            return;
        }

        try {
            GenericUtils.renameFile(getPrjRootDir(req), name, rename, extl, dname);
        } catch (WsSrvException e) {
            checkSendError(req, resp, e);
        }
    } else {
        try {
            if (!ServletFileUpload.isMultipartContent(req)) {
                //-- 255
                checkSendError(req, resp, 255, "Request is not multipart");
                return;
            }

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

            InputStream in = null;
            List<FileItem> items;
            try {
                items = upload.parseRequest(req);
            } catch (FileUploadException e) {
                //-- 256
                checkSendError(req, resp, 256, "Error parsing request", null, e);
                return;
            }

            for (FileItem fi : items) {
                if (!fi.isFormField()) {
                    in = fi.getInputStream();
                    break;
                }
            }

            if (in == null) {
                //-- 257
                checkSendError(req, resp, 257, "Multipart section is not found");
                return;
            }

            String res = ExFileUtils.createFile(getPrjRootDir(req), name, in, extl, dname,
                    getReqParamValues(req), getEntityUtils(req), isMinfied(req),
                    req.getParameter("overwrite") != null);
            printJson(resp, Utils.isEmpty(res) ? "{}" : res);
        } catch (WsSrvException e) {
            checkSendError(req, resp, e);
        }
    }
}

From source file:dk.dma.msinm.legacy.nm.LegacyNmImportRestService.java

/**
 * Imports an uploaded NtM PDF file/*  www .j av  a 2  s .com*/
 *
 * @param request the servlet request
 * @return a status
 */
@POST
@Path("/upload-pdf")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces("application/json;charset=UTF-8")
public String importPDF(@Context HttpServletRequest request) throws Exception {
    FileItemFactory factory = RepositoryService.newDiskFileItemFactory(servletContext);
    ServletFileUpload upload = new ServletFileUpload(factory);
    List<FileItem> items = upload.parseRequest(request);

    for (FileItem item : items) {
        if (!item.isFormField()) {
            // NM PDF
            if (NmPdfExtractor.getFileNameMatcher(item.getName()).matches()) {
                StringBuilder txt = new StringBuilder();
                importNmPdf(item.getInputStream(), item.getName(), txt);
                return txt.toString();

            } else if (ActiveTempPrelimNmPdfExtractor.getFileNameMatcher(item.getName()).matches()) {
                // Active P&T NM PDF
                StringBuilder txt = new StringBuilder();
                updateActiveNm(item.getInputStream(), item.getName(), txt);
                return txt.toString();
            }
        }
    }

    return "No valid PDF uploaded";
}

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

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

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

From source file:edu.cornell.mannlib.vitro.webapp.controller.freemarker.ImageUploadHelper.java

/**
 * The user has uploaded a new main image, but we're not ready to assign it
 * to them.//from w w  w . j  a v  a2s .c  o m
 * 
 * Put it into the file storage system, and attach it as a temp file on the
 * session until we need it.
 */
FileInfo storeNewImage(FileItem fileItem, VitroRequest vreq) {
    InputStream inputStream = null;
    try {
        inputStream = fileItem.getInputStream();
        String mimeType = getMimeType(fileItem);
        String filename = getSimpleFilename(fileItem);
        FileInfo fileInfo = uploadedFileHelper.createFile(filename, mimeType, inputStream);

        TempFileHolder.attach(vreq.getSession(), ATTRIBUTE_TEMP_FILE, fileInfo);

        return fileInfo;
    } catch (FileAlreadyExistsException e) {
        throw new IllegalStateException("Can't create the new image file.", e);
    } catch (IOException e) {
        throw new IllegalStateException("Can't create the new image file.", e);
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:es.sm2.openppm.plugin.synchronize.action.ImportSynchronizeAction.java

@Override
public PluginResponse process() {

    PluginResponse response = new HtmlResponse();

    if (isUserRole(Constants.ROLE_PMO) || isUserRole(Constants.ROLE_PM)) {
        int idProject = Integer.parseInt(getMultipartField("id"));

        boolean error = false;

        try {//w  w  w  . j ava2  s  .c  om

            FileItem dataFile = getMultipartFields().get("file");

            XStream xstream = XStreamUtil.createXStrean();
            ProjectSync projectSync = (ProjectSync) xstream.fromXML(dataFile.getInputStream());

            SynchronizeLogic logic = new SynchronizeLogic();

            Project project = logic.synchronize(idProject, projectSync);
            Projectcharter projectCharter = logic.synchronizeCharter(idProject, projectSync);

            response.addSessionAttribute("importData", projectSync);

            // Data for edit
            ContractTypeLogic contractTypeLogic = new ContractTypeLogic();
            CategoryLogic categoryLogic = new CategoryLogic();
            GeographyLogic geoLogic = new GeographyLogic();
            CustomerLogic customerLogic = new CustomerLogic();
            CustomertypeLogic customertypeLogic = new CustomertypeLogic();
            ResourceProfilesLogic resourceProfilesLogic = new ResourceProfilesLogic();
            PerformingOrgLogic performingOrgLogic = new PerformingOrgLogic();
            ProgramLogic programLogic = new ProgramLogic();
            StagegateLogic stagegateLogic = new StagegateLogic();

            // Parameters for template
            HashMap<String, Object> parameters = new HashMap<String, Object>();
            parameters.put("resourceBundle", getResourceBundle());
            parameters.put("customertypes", customertypeLogic.findByCompany(getUser()));
            parameters.put("categories", categoryLogic.findByRelation(Category.COMPANY, getCompany()));
            parameters.put("customers", customerLogic.searchByCompany(getCompany()));
            parameters.put("geographies", geoLogic.findByRelation(Geography.COMPANY, getCompany()));
            parameters.put("contractTypes",
                    contractTypeLogic.findByRelation(Contracttype.COMPANY, getCompany()));
            parameters.put("programs", programLogic.searchByPerfOrg(project.getPerformingorg()));
            parameters.put("perforgs", performingOrgLogic.findByRelation(Performingorg.COMPANY, getCompany()));
            parameters.put("profiles", resourceProfilesLogic.findAll());
            parameters.put("projectSync", projectSync);
            parameters.put("project", project);
            parameters.put("projectCharter", projectCharter);
            parameters.put("stageGates", stagegateLogic.findByRelation(Currency.COMPANY, getCompany()));
            parameters.put("data", createLabels());
            parameters.put("defaultcostVariance",
                    Boolean.parseBoolean(SettingUtil.getString(getSettings(),
                            Settings.SETTING_PROJECT_INIT_EXTERNAL_COST_SHOW,
                            Settings.DEFAULT_PROJECT_INIT_EXTERNAL_COST_SHOW)));
            parameters.put("defaultProbabilityVariance", ValidateUtil.isNull(SettingUtil.getList(getSettings(),
                    Settings.DEFAULT_PROJECT_PROBABILITY, Settings.DEFAULT_PROJECT_PROBABILITY)[0]));
            parameters.put("defaultProbability", SettingUtil.getList(getSettings(),
                    Settings.SETTING_PROJECT_PROBABILITY, Settings.DEFAULT_PROJECT_PROBABILITY));
            parameters.put("hasPermision", hasPermission(project));
            parameters.put("datePattern", DateUtil.getDatePattern(getResourceBundle()));
            parameters.put("disableValidate", checkValidate(project));
            parameters.put("optionalCurrecny", Boolean.valueOf(Settings.OPTIONAL_CURRENCY));
            parameters.put("currencyPattern", Constants.CURRENCY_FTL_PATTERN);

            // Generate HTML from template
            ((HtmlResponse) response).setData(PluginTemplate.getTemplate(
                    "/es/sm2/openppm/plugin/synchronize/template/load/SynchronizeLoad.ftl", parameters));

        } catch (Exception e) {
            error = true;
            addError(response, this.getClass(), e);
        }

        if (error) {
            response = new BeanResponse();
            ((BeanResponse) response).setUrlServlet("projectinit");
            ((BeanResponse) response).addData("idProject", getIdProject());
            ((BeanResponse) response).setInformationType(StringPool.ERROR);
            ((BeanResponse) response).setInformation("msg.error.bad_format_file");
        }
    }

    return response;
}

From source file:com.enonic.vertical.adminweb.AdminHandlerBaseServlet.java

public static BinaryData createBinaryData(final FileItem fileItem, final String label)
        throws VerticalAdminException {
    BinaryData binaryData = new BinaryData();
    InputStream fis = null;/*w  w  w.j  a  v a  2 s .  com*/
    try {
        binaryData.fileName = FileUtil.getFileName(fileItem);

        fis = fileItem.getInputStream();
        ByteArrayOutputStream bao = new ByteArrayOutputStream();

        byte[] buf = new byte[1024 * 10];
        int size;
        while ((size = fis.read(buf)) > 0) {
            bao.write(buf, 0, size);
        }
        binaryData.data = bao.toByteArray();
        binaryData.label = label;
    } catch (IOException e) {
        VerticalAdminLogger.errorAdmin(AdminHandlerBaseServlet.class, 20, "I/O error: %t", e);
    } finally {
        try {
            if (fis != null) {
                fis.close();
            }
        } catch (IOException ioe) {
            String message = "Failed to close file input stream: %t";
            VerticalAdminLogger.warn(AdminHandlerBaseServlet.class, 0, message, ioe);
        }
    }
    return binaryData;
}

From source file:UploadImage.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // change the following parameters to connect to the oracle database
    String username = "patzelt";
    String password = "Chocolate1";
    String drivername = "oracle.jdbc.driver.OracleDriver";
    String dbstring = "jdbc:oracle:thin:@gwynne.cs.ualberta.ca:1521:CRS";
    int photo_id;

    try {// w w w.ja va  2  s.co m
        // Parse the HTTP request to get the image stream
        DiskFileUpload fu = new DiskFileUpload();
        List FileItems = fu.parseRequest(request);

        // Process the uploaded items, assuming only 1 image file uploaded
        Iterator i = FileItems.iterator();
        FileItem item = (FileItem) i.next();
        while (i.hasNext() && item.isFormField()) {
            item = (FileItem) i.next();
        }
        long size = item.getSize();

        // Get the image stream
        InputStream instream = item.getInputStream();

        // Connect to the database and create a statement
        Connection conn = getConnected(drivername, dbstring, username, password);
        Statement stmt = conn.createStatement();

        /*
         * First, to generate a unique pic_id using an SQL sequence
         */
        ResultSet rset1 = stmt.executeQuery("SELECT pic_id_sequence.nextval from dual"); // good
        rset1.next();
        photo_id = rset1.getInt(1);
        /**
        // Insert an empty blob into the table first. Note that you have to
        // use the Oracle specific function empty_blob() to create an empty
        // blob
        stmt.execute("INSERT INTO pictures (photo_id, pic_des, pic) VALUES(" + photo_id + ",'test',empty_blob())");
                
        // to retrieve the lob_locator
        // Note that you must use "FOR UPDATE" in the select statement
        String cmd = "SELECT * FROM pictures WHERE photo_id = " + photo_id + " FOR UPDATE";
        ResultSet rset = stmt.executeQuery(cmd);
        rset.next();
        BLOB myblob = ((OracleResultSet) rset).getBLOB(3);
                
        **/

        stmt.execute("INSERT INTO pictures VALUES(" + photo_id + ",'test',empty_blob())");

        PreparedStatement stmt1 = conn
                .prepareStatement("UPDATE pictures SET pic = ? WHERE photo_id = + " + photo_id);
        stmt1.setBinaryStream(1, instream);
        stmt1.executeUpdate();

        /**
        // Write the image to the blob object
        OutputStream outstream = myblob.setBinaryStream(size);
        //int bufferSize = myblob.getBufferSize();
        //byte[] buffer = new byte[bufferSize];
        //int length = -1;
        //while ((length = instream.read(buffer)) != -1)
           //outstream.write(buffer, 0, length);
        outstream.write(pic);
        instream.close();
        outstream.close();
                
        //String update = "UPDATE pictures SET pic = " + myblob + " WHERE photo_id = " + photo_id;
        //stmt.execute(update);
        **/

        response_message = "YAHHOOOOOO";
        conn.close();

    } catch (Exception ex) {
        // System.out.println( ex.getMessage());
        response_message = ex.getMessage();
    }

    // Output response to the client
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " + "Transitional//EN\">\n" + "<HTML>\n"
            + "<HEAD><TITLE>Upload Message</TITLE></HEAD>\n" + "<BODY>\n" + "<H1>" + response_message
            + "</H1>\n" + "</BODY></HTML>");
}

From source file:com.ephesoft.gxt.admin.server.ImportTableUploadServlet.java

/**
 * This API is used to write content in temp file.
 * /*from  w  ww.  j a  v  a2s  .c om*/
 * @param item {@link FileItem} uploaded file item.
 * @param filePath {@link String} to create temporary file.
 * @param printWriter {@link PrintWriter}.
 * @return {@link File} temporary file.
 */
private File copyItemContentInFile(final FileItem item, final String filePath, final PrintWriter printWriter) {
    File tempTableFile = null;
    OutputStream out = null;
    InputStream instream = null;
    try {
        instream = item.getInputStream();
        tempTableFile = new File(filePath);
        //         if (tempTableFile.exists()) {
        //            tempTableFile.delete();
        //         }
        out = new FileOutputStream(tempTableFile);
        final byte buf[] = new byte[1024];
        int len;
        while ((len = instream.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
    } catch (final FileNotFoundException e) {
        printWriter.write("Unable to create the export folder.Please try again.");
    } catch (final IOException e) {
        printWriter.write("Unable to read the file.Please try again.");
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (final IOException ioe) {
                log.error("Could not close stream for file." + tempTableFile);
            }
        }
        if (instream != null) {
            try {
                instream.close();
            } catch (final IOException ioe) {
                log.error("Could not close stream for file." + filePath);
            }
        }
    }
    return tempTableFile;
}