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

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

Introduction

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

Prototype

byte[] get();

Source Link

Document

Returns the contents of the file item as an array of bytes.

Usage

From source file:pt.webdetails.cfr.CfrContentGenerator.java

@Exposed(accessLevel = AccessLevel.PUBLIC, outputType = MimeType.JSON)
public void store(OutputStream out) throws IOException, InvalidOperationException, Exception {

    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    List /* FileItem */ items = upload.parseRequest(getRequest());

    String fileName = null, savePath = null;
    byte[] contents = null;
    for (int i = 0; i < items.size(); i++) {
        FileItem fi = (FileItem) items.get(i);

        if ("path".equals(fi.getFieldName())) {
            savePath = fi.getString();/*from   www  .j  a v a 2 s.c om*/
        }
        if ("file".equals(fi.getFieldName())) {
            contents = fi.get();
            fileName = fi.getName();
        }
    }

    if (fileName == null) {
        logger.error("parameter fileName must not be null");
        throw new Exception("paramete fileName must not be null");
    }
    if (savePath == null) {
        logger.error("parameter path must not be null");
        throw new Exception("parameter path must not be null");
    }
    if (contents == null) {
        logger.error("File content must not be null");
        throw new Exception("File content must not be null");
    }

    FileStorer fileStorer = new FileStorer(service.getRepository());

    boolean stored = fileStorer.storeFile(checkRelativePathSanity(fileName), checkRelativePathSanity(savePath),
            contents, userSession.getName());

    JSONObject result = new JSONObject().put("result", stored);
    writeOut(out, result.toString());
}

From source file:Servlets.AddNewVendor.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    HttpSession session = request.getSession(true);
    NewVendorBean bean = new NewVendorBean();
    try {/*from  w w w.  ja v a2  s.c  o m*/
        DiskFileItemFactory factory = new DiskFileItemFactory();

        ServletFileUpload sfu = new ServletFileUpload(factory);
        List items = sfu.parseRequest(request);

        Iterator iter = items.iterator();//out.print("  1");

        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            String fieldName = item.getFieldName();
            switch (fieldName) {
            case "mailID":
                bean.setEmail(item.getString());//out.print(" 1 "+email+"<br> ");
                break;
            case "pass":
                bean.setPass(item.getString());//out.print(" 3 "+pass+" <br>");
                break;
            case "questions":
                bean.setQus(item.getString());//out.print(" 3 "+pass+" <br>");
                break;
            case "ans":
                bean.setAns(item.getString());//out.print(" 3 "+pass+" <br>");
                break;
            case "firmName":
                bean.setCompanyName(item.getString());//out.print(" 5 "+companyName+" <br>");
                break;
            case "phno":
                bean.setPhno1(item.getString()); //out.print(" 6 "+phno1+" <br>");
                break;
            case "phno2":
                bean.setPhno2(item.getString());//out.print(" 7 "+phno2+" <br>");
                break;
            case "address":
                bean.setAddress(item.getString());//out.print(" 8 "+address+" <br>");
                break;
            case "SAN":
                bean.setSAN(item.getString());//out.print(" 9 "+SAN+" <br>");
                break;
            case "CST":
                bean.setCST(item.getString());//out.print(" 10 "+CST+" <br>");
                break;
            case "VAT":
                bean.setVAT(item.getString());//out.print(" 11 "+VAT+" <br>");
                break;
            case "PAN":
                bean.setPAN(item.getString());//out.print(" 12 "+PAN+" <br>");
                break;
            case "TAN":
                bean.setTAN(item.getString());//out.print(" 13 "+TAN+" <br>");
                break;
            case "web":
                bean.setWeb(item.getString());//out.print(" 14 "+web+" <br>");
                break;
            case "IT":
                bean.setB(item.get());
                break;
            case "skilled":
                bean.setSkilled(item.getString());//out.print(" 25 "+skilled+" <br>");
                break;
            case "nonSkilled":
                bean.setNonSkilled(item.getString());//out.print(" 26 "+nonSkilled+" <br>");
                break;

            case "category":
                switch (item.getString()) {
                case "Benches":
                    bean.setBench(true);
                    break;
                case "Black Board":
                    bean.setBlackbord(true);
                    break;
                case "Books":
                    bean.setBook(true);
                    break;
                case "Chemical Material":
                    bean.setChemical(true);
                    break;
                case "Glassware Material":
                    bean.setGlassware(true);
                    break;
                case "I-card & material":
                    bean.setIcard(true);
                    break;
                case "Sports Material":
                    bean.setSports(true);
                    break;
                case "Steal Furniture":
                    bean.setSteel(true);
                    break;
                case "Wooden Furniture":
                    bean.setWooden(true);
                    break;
                case "Science Instruments":
                    bean.setScienceInstru(true);
                    break;

                }
            }
        }
        VendorRegistrationDao dao = new VendorRegistrationDao();
        String result = dao.addVendor(bean);
        out.print(result);
        if (result.equals("SUCCESS")) {
            session.setAttribute("result", "SUCCESS");
            session.setAttribute("ID", bean.getEmail());
            response.sendRedirect("registrationSuccess.jsp");
        } else {
            session.setAttribute("result", "ERROR");
            response.sendRedirect("registrationSuccess.jsp");
        }

    } catch (Exception e) {
        e.printStackTrace(new java.io.PrintWriter(out));
    }

}

From source file:tilt.handler.post.TiltTestHandler.java

/**
 * Parse the import params from the request
 * @param request the http request//from ww  w .ja v  a2 s  .  c o m
 */
private void parseImportParams(HttpServletRequest request) throws TiltException {
    try {
        FileItemFactory factory = new DiskFileItemFactory();
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        // Parse the request
        List items = upload.parseRequest(request);
        for (int i = 0; i < items.size(); i++) {
            FileItem item = (FileItem) items.get(i);
            if (item.isFormField()) {
                String fieldName = item.getFieldName();
                if (fieldName != null) {
                    if (fieldName.equals(Params.ENCODING)) {
                        encoding = item.getString();
                    } else if (fieldName.equals(Params.PICTYPE)) {
                        picType = ImageType.read(item.getString());
                    } else if (fieldName.equals(Params.TEXT)) {
                        text = new TextIndex(item.getString(), "en_GB");
                    }
                }
            } else if (item.getName().length() > 0) {
                try {
                    // assuming that the contents are text
                    // item.getName retrieves the ORIGINAL file name
                    String type = item.getContentType();
                    if (type != null && type.startsWith("application/")) {
                        byte[] rawData = item.get();
                        //System.out.println(encoding);
                        geoJSON = new String(rawData, encoding);
                    }
                } catch (Exception e) {
                    throw new TiltException(e);
                }
            }
        }
    } catch (Exception e) {
        throw new TiltException(e);
    }
}

From source file:uk.ac.lancs.e_science.fileUpload.UploadRenderer.java

public void decode(FacesContext context, UIComponent component) {
    ExternalContext external = context.getExternalContext();
    HttpServletRequest request = (HttpServletRequest) external.getRequest();
    String clientId = component.getClientId(context);
    FileItem item = (FileItem) request.getAttribute(clientId);

    Object newValue;/*from  w  w  w .jav a2  s  . co  m*/
    ValueBinding binding = component.getValueBinding("value");
    if (binding != null) {
        if (binding.getType(context) == byte[].class) {
            newValue = item.get();
        }
        if (binding.getType(context) == FileItem.class) {
            newValue = item;
        } else {
            String encoding = request.getCharacterEncoding();
            if (encoding != null)
                try {
                    newValue = item.getString(encoding);
                } catch (UnsupportedEncodingException ex) {
                    newValue = item.getString();
                }
            else
                newValue = item.getString();
        }
        ((EditableValueHolder) component).setSubmittedValue(newValue);
    }

    Object target;
    binding = component.getValueBinding("target");
    if (binding != null)
        target = binding.getValue(context);
    else
        target = component.getAttributes().get("target");

}

From source file:uk.ac.lancs.e_science.sakai.tools.blogger.PostEditionAbstractController.java

public void setImage(FileItem fileItem) {
    treatingImageAsFile = false;/*from w w  w . ja  v a2 s  . c  o m*/
    if (fileItem != null && fileItem.get() != null && fileItem.get().length > 0) {
        byte[] content = fileItem.get();
        try {
            if (content != null) {
                if (content.length < 4 * 1024 * 1024) { // TODO put that 4 Mb in a property
                    editedImage = new Image(fileItem.getName(), content);
                    imageDescription = fileItem.getName();
                    if (imageDescription.indexOf(":\\") == 1) // we assume that is a windows file comming from ie
                        imageDescription = imageDescription.substring(imageDescription.lastIndexOf("\\") + 1);
                    JpegTransformer transformer = new JpegTransformer(content);
                    editedImage.setDescription(imageDescription);
                    editedImage.setImageContentWithThumbnailSize(
                            transformer.transformJpegFixingLongestDimension(125, 0.8f));
                    editedImage.setImageContentWithWebSize(
                            transformer.transformJpegFixingLongestDimension(300, 0.8f));
                } else {
                    editedImage = null;
                    imageDescription = "";
                    setFile(fileItem.getName(), content);
                    treatingImageAsFile = true;
                }
            }
        } catch (Exception e) {
            // if we can not treat the Image because of the format, it will be treat as a file
            editedImage = null;
            imageDescription = "";
            setFile(fileItem.getName(), content);
            treatingImageAsFile = true;
        }
    }
}

From source file:uk.ac.lancs.e_science.sakai.tools.blogger.PostEditionAbstractController.java

public void setFile(FileItem i) {
    if (i != null && i.get() != null && i.get().length > 0) {
        try {/*w w w .ja  v a2  s  .c o m*/
            byte[] content = i.get();
            String name = i.getName();
            if (name.indexOf(":\\") == 1) // we assume that is a windows file comming from ie
                name = name.substring(name.lastIndexOf("\\") + 1);
            setFile(name, content);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:unUtils.WikittyPublicationContext.java

/**
 * set attributes://from   w ww.j  av a2 s  .  com
 * <li> req
 * <li> wsContext
 * <li> actionName
 * <li> mandatoryArguments
 * <li> arguments
 *
 * @param req
 */
public void parse(HttpServletRequest req, HttpServletResponse resp) {
    this.req = req;
    this.resp = resp;

    String path = req.getPathInfo();

    // path start with '/' then comps[0] == empty
    String[] comps = StringUtil.split(path, "/");
    if (comps.length > 0) {
        wsContext = comps[1];
    }
    if (comps.length > 1) {
        actionName = comps[2];
    }

    for (int i = 3; i < comps.length; i++) {
        mandatoryArguments.add(comps[i]);
        path += "/" + comps[i];
    }

    boolean isMultipart = ServletFileUpload.isMultipartContent(getRequest());
    if (isMultipart == true) {
        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        // Process the uploaded items
        // Parse the request
        try {
            List<FileItem> items = upload.parseRequest(getRequest());
            for (FileItem item : items) {
                String name = item.getFieldName();
                if (item.isFormField()) {
                    String value = item.getString();
                    arguments.put(name, value);
                } else {
                    String filename = item.getName();
                    String mime = item.getContentType();
                    byte[] value = item.get();
                    log.info(String.format("Argument file '%s' of type '%s'", filename, mime));
                    argumentFiles.put(name, value);
                    arguments.put(name + "-upload", "true");
                    arguments.put(name + "-filename", filename);
                    arguments.put(name + "-contentType", mime);
                }
            }
        } catch (FileUploadException eee) {
            log.error("Can't get uploaded file", eee);
        }
    } else {
        for (Enumeration<String> e = req.getParameterNames(); e.hasMoreElements();) {
            String name = e.nextElement();
            String value = req.getParameter(name);
            arguments.put(name, value);
        }
    }
    log.info(String.format("path %s => ws: %s action: %s mandatoryArguments: %s arguments: %s", path, wsContext,
            actionName, mandatoryArguments, arguments));
}

From source file:view.SubirImagen.java

/**
 * Processes requests for both HTTP <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request//  w  w w . ja va2s .c  o m
 * @param response servlet response
 *
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        ImagenJpaController ijc = new ImagenJpaController(utx, emf);
        MimeTypeJpaController mjc = new MimeTypeJpaController(utx, emf);
        model.Imagen imagen = new model.Imagen();
        dirUploadFiles = "imagenes/";
        if (ServletFileUpload.isMultipartContent(request)) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setSizeMax(Long.MAX_VALUE);

            List listUploadFiles = null;
            FileItem item = null;

            try {

                listUploadFiles = upload.parseRequest(request);

                Iterator it = listUploadFiles.iterator();
                while (it.hasNext()) {
                    item = (FileItem) it.next();

                    if (!item.isFormField()) {

                        if (item.getSize() > 0) {

                            String nombre = item.getName();
                            imagen.setNombre(nombre);
                            String tipo = item.getContentType();
                            MimeType mimeType = mjc.findMimeType(tipo);
                            imagen.setMimeTypeId(mimeType);
                            imagen.setRuta(dirUploadFiles + nombre);
                            long tamanio = item.getSize();
                            String extension = nombre.substring(nombre.lastIndexOf("."));
                            imagen.setContenido(item.get());
                            ijc.create(imagen);
                            out.println("Nombre: " + nombre + "<br>");
                            out.println("Tipo: " + tipo + "<br>");
                            out.println("Extension: " + extension + "<br>");
                            out.println("GUARDADO " + imagen.getRuta() + "</p>");
                            out.println("<a href='/Documentos/ListaImagenes'>Imagenes Subidas </a>");
                        }
                    }
                }

            } catch (FileUploadException e) {
                e.printStackTrace();
            } catch (Exception e) {
                // poner respuesta = false; si existe alguna problema
                e.printStackTrace();
            }
        }
        out.println("Fin de la operacion! ;)");
        out.close();
    }

}

From source file:Vista.Carga.java

/**
 * Processes requests for both HTTP <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request/* w  w w  .ja  va 2 s .  c o m*/
 * @param response servlet response
 *
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    CargaArchivo c = new CargaArchivo();

    if (ServletFileUpload.isMultipartContent(request)) {

        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(Long.MAX_VALUE);

        List listUploadFiles = null;
        FileItem item = null;

        try {
            listUploadFiles = upload.parseRequest(request);

            Iterator it = listUploadFiles.iterator();
            while (it.hasNext()) {
                item = (FileItem) it.next();
                if (!item.isFormField()) {
                    if (item.getSize() > 0) {
                        String nombre = item.getName();
                        String tipo = item.getContentType();

                        long tamanio = item.getSize();

                        String extension = nombre.substring(nombre.lastIndexOf("."));

                        out.println("Nombre: " + nombre + "<br>");
                        out.println("Tipo: " + tipo + "<br>");
                        out.println("Extension: " + extension + "<br>");
                        Archivo a = new Archivo();
                        a.setContenido(item.get());
                        MimeType m = new MimeType();
                        m.setId(1);
                        m.setNombre("PDF");
                        a.setMimeTypeId(m);
                        a.setNombre(item.getName());
                        a.setPath("/files");
                        c.cargaArchivo(a);
                        out.println("GUARDADO " + a.getNombre() + "</p>");

                    }
                }
            }

        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    out.println("Fin de la operacion! ;)");
    out.close();
}

From source file:web.AddsiteblobController.java

/**
 * This method is called by the spring framework. The configuration
 * for this controller to be invoked is based on the pagetype and
 * is set in the urlMapping property in the spring config file.
 *
 * @param request the <code>HttpServletRequest</code>
 * @param response the <code>HttpServletResponse</code>
 * @throws ServletException/*from   ww  w  .j a v  a2  s. c o m*/
 * @throws IOException
 * @return ModelAndView this instance is returned to spring
 */
public synchronized ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {
        ModelAndView m = super.handleRequest(request, response);
    } catch (Exception e) {
        return handleError("error in handleRequest", e);
    }
    outOfSession(request, response);

    if (!DiaryAdmin.isDiaryAdmin(login)) {
        return handleError("Cannot add site cobrand as login is not Admin.");
    }

    if (RegexStrUtil.isNull(login) || (loginInfo == null)) {
        return handleUserpageError("Login/loginInfo is null.");
    }

    // remember any request parameters have to be added thru the field list.
    // cannot use request.getParameter in this program.

    String vhostid = request.getParameter(DbConstants.VHOST_ID);
    if (RegexStrUtil.isNull(vhostid)) {
        return handleError("vhostid is null in AddsiteblobController");
    }
    vhostid = RegexStrUtil.goodNameStr(vhostid);

    Integer blobtype = new Integer(request.getParameter(DbConstants.BLOBTYPE));
    if (blobtype < GlobalConst.categoryMinSize || blobtype > GlobalConst.categoryMaxSize) {
        return handleUserpageError("category or blobtype is not appropriate type in AddsiteblobController");
    }

    byte[] blob = null;
    String mtype = null;
    String btitle = null;
    int zoom = 100;
    List fileList = null;
    DiskFileUpload upload = null;
    try {
        boolean isMultipart = FileUpload.isMultipartContent(request);
        // Create a new file upload handler
        upload = new DiskFileUpload();
        //upload.setSizeMax((long)10000000);
        //upload.setSizeMax(webConstants.getFileuploadsize());
        upload.setSizeMax(GlobalConst.fileUploadSize);

        // Parse the request
        fileList = upload.parseRequest(request);
    } catch (Exception e) {
        return handleError("Exception occurred in uploading the photo file.", e);
    }

    long fieldsize = 0;

    for (int i = 0; i < fileList.size(); i++) {
        FileItem fileItem = (FileItem) fileList.get(i);
        if (!fileItem.isFormField()) {
            blob = fileItem.get();
            mtype = fileItem.getContentType();
            long maxSize = upload.getSizeMax();
            fieldsize = fileItem.getSize();
        }
    }

    boolean addBlob = true;
    if ((fieldsize <= 0) || (RegexStrUtil.isNull(mtype))) {
        addBlob = false;
    }

    String loginid = loginInfo.getValue(DbConstants.LOGIN_ID);
    if (getDaoMapper() == null) {
        return handleError("DaoMapper is null in AddsiteblobController");
    }

    CobrandSiteDao cobrandSiteDao = (CobrandSiteDao) getDaoMapper().getDao(DbConstants.COBRAND_SITE);
    if (cobrandSiteDao == null) {
        return handleError("cobrandSiteDao is null for AddsiteblobController");
    }

    String ftype = request.getParameter(DbConstants.TYPE);

    if (RegexStrUtil.isNull(ftype)) {
        return handleError("ftype is null for AddsiteblobController");
    }

    if (!ftype.equals(DbConstants.COBRAND_HEADER) && !ftype.equals(DbConstants.COBRAND_FOOTER)) {
        return handleError("cobrand filetype is neither a header nor footer AddsiteblobController");
    }

    if (vhostid.length() > GlobalConst.entryIdSize) {
        return handleError("vhostid.length() > WebConstants.entryIdSize,in AddsiteblobController");
    }

    /**
     *  If the blob information is provided by the user, add the blob
     */
    String blobtypeStr = request.getParameter(DbConstants.BLOBTYPE);
    List sites = null;
    if (addBlob) {
        try {
            cobrandSiteDao.addCobrandStreamBlob(blob, vhostid, ftype, loginid, login);
            sites = cobrandSiteDao.getSites(DbConstants.READ_FROM_MASTER, login, loginid);
        } catch (BaseDaoException e) {
            return handleError("Exception occurred in addBlob() addSiteCobrandStream ", e);
        }
    }

    Map myModel = new HashMap();
    String viewName = DbConstants.EDIT_SITE_COBRAND;
    myModel.put(DbConstants.COBRAND, sites);
    myModel.put(DbConstants.DIR_EXISTS, rbDirectoryExists);
    myModel.put(DbConstants.USER_PAGE, userpage);
    myModel.put(DbConstants.LOGIN_INFO, loginInfo);
    myModel.put(DbConstants.BUSINESS_EXISTS, isBizExists(login));
    return new ModelAndView(viewName, "model", myModel);

}