Example usage for org.apache.commons.fileupload FileItemStream isFormField

List of usage examples for org.apache.commons.fileupload FileItemStream isFormField

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItemStream isFormField.

Prototype

boolean isFormField();

Source Link

Document

Determines whether or not a FileItem instance represents a simple form field.

Usage

From source file:com.runwaysdk.web.SecureFileUploadServlet.java

protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    ClientRequestIF clientRequest = (ClientRequestIF) req.getAttribute(ClientConstants.CLIENTREQUEST);

    boolean isMultipart = ServletFileUpload.isMultipartContent(req);

    if (!isMultipart) {
        // TODO Change exception type
        String msg = "The HTTP Request must contain multipart content.";
        throw new RuntimeException(msg);
    }//from  www.ja  v  a  2s.com

    String fileId = req.getParameter("sessionId").toString().trim();
    FileItemFactory factory = new ProgressMonitorFileItemFactory(req, fileId);
    ServletFileUpload upload = new ServletFileUpload();

    upload.setFileItemFactory(factory);

    try {
        // Parse the request

        FileItemIterator iter = upload.getItemIterator(req);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();

            if (!item.isFormField()) {
                String fullName = item.getName();
                int extensionInd = fullName.lastIndexOf(".");
                String fileName = fullName.substring(0, extensionInd);
                String extension = fullName.substring(extensionInd + 1);
                InputStream stream = item.openStream();

                BusinessDTO fileDTO = clientRequest.newSecureFile(fileName, extension, stream);

                // return the vault id to the dhtmlxVault callback
                req.getSession().setAttribute("FileUpload.Progress." + fileId, fileDTO.getId());
            }
        }
    } catch (FileUploadException e) {
        throw new FileWriteExceptionDTO(e.getLocalizedMessage());
    } catch (RuntimeException e) {
        req.getSession().setAttribute("FileUpload.Progress." + fileId, "fail: " + e.getLocalizedMessage());
    }
}

From source file:com.northernwall.hadrian.handler.ImageHandler.java

private void updateImage(Request request, String serviceId) throws IOException, FileUploadException {
    if (!ServletFileUpload.isMultipartContent(request)) {
        logger.warn("Trying to upload image for {} but content is not multipart", serviceId);
        return;//  w  ww.ja  va 2  s  .  c o m
    }
    logger.info("Trying to upload image for {}", serviceId);
    ServletFileUpload upload = new ServletFileUpload();

    // Parse the request
    FileItemIterator iter = upload.getItemIterator(request);
    while (iter.hasNext()) {
        FileItemStream item = iter.next();
        if (!item.isFormField()) {
            String name = item.getName();
            name = name.replace(' ', '-').replace('&', '-').replace('<', '-').replace('>', '-')
                    .replace('/', '-').replace('\\', '-').replace('&', '-').replace('@', '-').replace('?', '-')
                    .replace('^', '-').replace('#', '-').replace('%', '-').replace('=', '-').replace('$', '-')
                    .replace('{', '-').replace('}', '-').replace('[', '-').replace(']', '-').replace('|', '-')
                    .replace(';', '-').replace(':', '-').replace('~', '-').replace('`', '-');
            dataAccess.uploadImage(serviceId, name, item.getContentType(), item.openStream());
        }
    }
}

From source file:com.example.getstarted.basicactions.CreateBookServlet.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    assert ServletFileUpload.isMultipartContent(req);
    CloudStorageHelper storageHelper = (CloudStorageHelper) getServletContext().getAttribute("storageHelper");

    String newImageUrl = null;//from   w w w  .ja  va  2s .  c  o  m
    Map<String, String> params = new HashMap<String, String>();
    try {
        FileItemIterator iter = new ServletFileUpload().getItemIterator(req);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            if (item.isFormField()) {
                params.put(item.getFieldName(), Streams.asString(item.openStream()));
            } else if (!Strings.isNullOrEmpty(item.getName())) {
                newImageUrl = storageHelper.uploadFile(item,
                        getServletContext().getInitParameter("bookshelf.bucket"));
            }
        }
    } catch (FileUploadException e) {
        throw new IOException(e);
    }

    String createdByString = "";
    String createdByIdString = "";
    HttpSession session = req.getSession();
    if (session.getAttribute("userEmail") != null) { // Does the user have a logged in session?
        createdByString = (String) session.getAttribute("userEmail");
        createdByIdString = (String) session.getAttribute("userId");
    }

    Book book = new Book.Builder().author(params.get("author")).description(params.get("description"))
            .publishedDate(params.get("publishedDate")).title(params.get("title"))
            .imageUrl(null == newImageUrl ? params.get("imageUrl") : newImageUrl).createdBy(createdByString)
            .createdById(createdByIdString).build();

    BookDao dao = (BookDao) this.getServletContext().getAttribute("dao");
    try {
        Long id = dao.createBook(book);
        logger.log(Level.INFO, "Created book {0}", book);
        resp.sendRedirect("/read?id=" + id.toString()); // read what we just wrote
    } catch (Exception e) {
        throw new ServletException("Error creating book", e);
    }
}

From source file:Functions.UploadFileServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String houseId = "";
    String owner = (String) request.getSession().getAttribute("username");
    String url = "/errorPage.jsp";
    String message = "fgd";
    //System.out.println("houseId= "+houseId);
    //System.out.println("owner= "+owner);
    response.setContentType("text/html");
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        ServletFileUpload upload = new ServletFileUpload();
        try {//from w w w  . ja v  a  2  s .  c o  m
            FileItemIterator itr = upload.getItemIterator(request);
            while (itr.hasNext()) {
                FileItemStream item = itr.next();
                if (item.isFormField()) {
                    //do something
                    String fieldName = item.getFieldName();
                    InputStream is = item.openStream();
                    byte b[] = new byte[is.available()];
                    is.read(b);
                    String value = new String(b);
                    if ("houseIddd".equals(fieldName)) {
                        houseId = value;
                    }
                    response.getWriter().println(fieldName + ":" + value + "<br/>");
                } else {
                    System.out.println("MPHKE STO ELSE GIA NA BALEI SPITIA");
                    //upload file
                    String path = getServletContext().getRealPath("/");
                    //String path = getServletContext().getContextPath()+"/";

                    if (FileUpload.processFile(path, item, houseId, owner)) {
                        System.out.println("MPHKE STO processfile!");
                        //response.getWriter().println("file uploaded successfully");
                        message = "file uploaded successfully";

                        url = "/Estateprofile.jsp?houseId=" + houseId + "&houseOwner=" + owner + "&message="
                                + message;

                    } else {
                        message = "file uploading failed";
                        url = "/Estateprofile.jsp?houseId=" + houseId + "&houseOwner=" + owner + "&message="
                                + message;

                        //response.getWriter().println("file uploading failed");
                    }
                }
            }
        } catch (FileUploadException ex) {
            ex.printStackTrace();
            //Logger.getLogger(UploadFileServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
        dispatcher.forward(request, response);
    }
}

From source file:DBMS.PicUpdateServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request// w w w.  ja v a 2 s  .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 {
    response.setContentType("text/html;charset=UTF-8");
    boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
    if (isMultiPart) {
        ServletFileUpload upload = new ServletFileUpload();
        try {
            FileItemIterator itr = upload.getItemIterator(request);
            while (itr.hasNext()) {
                FileItemStream item = itr.next();
                if (item.isFormField()) {
                    String fieldName = item.getFieldName();
                    InputStream is = item.openStream();
                    byte[] b = new byte[is.available()];
                    is.read(b);
                    String value = new String(b);
                    System.out.println("Getting");
                } else {
                    String path = getServletContext().getRealPath("/");
                    loginid lid = null;
                    HttpSession session = request.getSession();
                    lid = (loginid) session.getAttribute("lid");
                    int id = lid.getId();
                    if (UpdateFileUpload.processFile(path, item, id)) {
                        response.sendRedirect("ProfilePicUpdateSuccess.jsp");
                    } else
                        response.sendRedirect("ProfilePicUpdateFailed.jsp");
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
    }
}

From source file:es.eucm.mokap.backend.server.MokapBackend.java

/**
 * Iterates the whole request in search for a file. When it finds it, it
 * creates a FileItemStream which contains it.
 * /* ww  w.j a va 2  s  .c o  m*/
 * @param req
 *            The request to process
 * @return Returns THE FIRST file found in the upload request or null if no
 *         file could be found
 */
private FileItemStream getUploadedFile(HttpServletRequest req) throws IOException, FileUploadException {
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload();
    // Set the UTF-8 encoding to grab the correct uploaded filename,
    // especially for Chinese
    upload.setHeaderEncoding("UTF-8");

    FileItemStream file = null;

    /* Parse the request */
    FileItemIterator iter = upload.getItemIterator(req);
    while (iter.hasNext()) {
        FileItemStream item = iter.next();
        if (!item.isFormField()) {
            file = item;
            break;
        }
    }
    return file;
}

From source file:com.vmware.photon.controller.api.frontend.resources.vm.VmIsoAttachResource.java

private Task parseIsoDataFromRequest(HttpServletRequest request, String id)
        throws InternalException, ExternalException {
    Task task = null;/*from  w ww  .j  a va 2s.c o  m*/

    ServletFileUpload fileUpload = new ServletFileUpload();
    List<InputStream> dataStreams = new LinkedList<>();

    try {
        FileItemIterator iterator = fileUpload.getItemIterator(request);
        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            if (item.isFormField()) {
                logger.warn(String.format("The parameter '%s' is unknown in attach ISO.", item.getFieldName()));
            } else {
                InputStream fileStream = item.openStream();
                dataStreams.add(fileStream);

                task = vmFeClient.attachIso(id, fileStream, item.getName());
            }
        }
    } catch (IOException ex) {
        throw new IsoUploadException("Iso upload IOException", ex);
    } catch (FileUploadException ex) {
        throw new IsoUploadException("Iso upload FileUploadException", ex);
    } finally {
        for (InputStream stream : dataStreams) {
            try {
                stream.close();
            } catch (IOException | NullPointerException ex) {
                logger.warn("Unexpected exception closing data stream.", ex);
            }
        }
    }

    if (task == null) {
        throw new IsoUploadException("There is no iso stream data in the iso upload request.");
    }

    return task;
}

From source file:com.webpagebytes.cms.controllers.ExportImportController.java

public void importContent(HttpServletRequest request, HttpServletResponse response, String requestUri)
        throws WPBException {
    File tempFile = null;/*from  w  ww  . j ava 2  s. com*/
    try {
        ServletFileUpload upload = new ServletFileUpload();

        FileItemIterator iterator = upload.getItemIterator(request);
        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            if (!item.isFormField() && item.getFieldName().equals("file")) {
                InputStream is = item.openStream();
                tempFile = File.createTempFile("wpbImport", null);
                FileOutputStream fos = new FileOutputStream(tempFile);
                IOUtils.copy(is, fos);
                fos.close();

                adminStorage.stopNotifications();
                deleteAll();

                // because the zip file entries cannot be predicted we needto import in two step1
                // step 1 when we create the resource records
                // step 2 when we import the files, pages, modules and articles content
                InputStream is1 = new FileInputStream(tempFile);
                storageExporter.importFromZipStep1(is1);
                is1.close();

                InputStream is2 = new FileInputStream(tempFile);
                storageExporter.importFromZipStep2(is2);
                is2.close();

                org.json.JSONObject returnJson = new org.json.JSONObject();
                returnJson.put(DATA, "");
                httpServletToolbox.writeBodyResponseAsJson(response, returnJson, null);
            }
        }
    } catch (Exception e) {
        Map<String, String> errors = new HashMap<String, String>();
        errors.put("", WPBErrors.WB_CANNOT_IMPORT_PROJECT);
        httpServletToolbox.writeBodyResponseAsJson(response, jsonObjectConverter.JSONObjectFromMap(null),
                errors);
    } finally {
        if (tempFile != null) {
            if (!tempFile.delete()) {
                tempFile.deleteOnExit();
            }
        }

        adminStorage.startNotifications();
    }
}

From source file:guru.nidi.ramltester.util.FormDecoder.java

private Object valueOf(FileItemStream itemStream) throws IOException {
    if (itemStream.isFormField()) {
        final String charset = charset(itemStream.getContentType());
        return IoUtils.readIntoString(new InputStreamReader(itemStream.openStream(), charset));
    }/*  ww w  . ja  v  a  2s  .c o  m*/
    return new FileValue();
}

From source file:br.com.ifpb.bdnc.projeto.geo.servlets.CadastraImagem.java

private Image mountImage(HttpServletRequest request) {
    Image image = new Image();
    image.setCoord(new Coordenate());
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        ServletFileUpload upload = new ServletFileUpload();
        try {/*from ww w.jav a  2s  .  c  om*/
            FileItemIterator itr = upload.getItemIterator(request);
            while (itr.hasNext()) {
                FileItemStream item = itr.next();
                if (item.isFormField()) {
                    InputStream in = item.openStream();
                    byte[] b = new byte[in.available()];
                    in.read(b);
                    if (item.getFieldName().equals("description")) {
                        image.setDescription(new String(b));
                    } else if (item.getFieldName().equals("authors")) {
                        image.setAuthors(new String(b));
                    } else if (item.getFieldName().equals("end")) {
                        image.setDate(
                                LocalDate.parse(new String(b), DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                    } else if (item.getFieldName().equals("latitude")) {
                        image.getCoord().setLat(new String(b));
                    } else if (item.getFieldName().equals("longitude")) {
                        image.getCoord().setLng(new String(b));
                    } else if (item.getFieldName().equals("heading")) {
                        image.getCoord().setHeading(new String(b));
                    } else if (item.getFieldName().equals("pitch")) {
                        image.getCoord().setPitch(new String(b));
                    } else if (item.getFieldName().equals("zoom")) {
                        image.getCoord().setZoom(new String(b));
                    }
                } else {
                    if (!item.getName().equals("")) {
                        MultipartData md = new MultipartData();
                        String folder = "historicImages";
                        md.setFolder(folder);
                        String path = request.getServletContext().getRealPath("/");
                        System.out.println(path);
                        String nameToSave = "pubImage" + Calendar.getInstance().getTimeInMillis()
                                + item.getName();
                        image.setImagePath(folder + "/" + nameToSave);
                        md.saveImage(path, item, nameToSave);
                        String imageMinPath = folder + "/" + "min" + nameToSave;
                        RedimencionadorImagem.resize(path, folder + "/" + nameToSave,
                                path + "/" + imageMinPath.toString(), IMAGE_MIN_WIDTH, IMAGE_MIM_HEIGHT);
                        image.setMinImagePath(imageMinPath);
                    }
                }
            }
        } catch (FileUploadException | IOException ex) {
            System.out.println("Erro ao manipular dados");
        }
    }
    return image;
}