Example usage for org.apache.commons.fileupload.servlet ServletFileUpload isMultipartContent

List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload isMultipartContent

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.servlet ServletFileUpload isMultipartContent.

Prototype

public static final boolean isMultipartContent(HttpServletRequest request) 

Source Link

Document

Utility method that determines whether the request contains multipart content.

Usage

From source file:mml.handler.post.MMLPostResourceHandler.java

@Override
public void handle(HttpServletRequest request, HttpServletResponse response, String urn) throws MMLException {
    try {//from   w ww .j a v  a2  s  . c  om
        if (ServletFileUpload.isMultipartContent(request)) {
            parseImportParams(request);
            for (int i = 0; i < files.size(); i++) {
                String style = files.get(i);
                JSONObject jDoc = new JSONObject();
                jDoc.put(JSONKeys.BODY, style);
                if (this.author != null)
                    jDoc.put(JSONKeys.AUTHOR, this.author);
                if (this.title != null)
                    jDoc.put(JSONKeys.TITLE, this.title);
                if (this.style != null)
                    jDoc.put(JSONKeys.STYLE, this.style);
                if (this.format != null)
                    jDoc.put(JSONKeys.FORMAT, this.format);
                if (this.section != null)
                    jDoc.put(JSONKeys.SECTION, this.section);
                if (this.version1 != null)
                    jDoc.put(JSONKeys.VERSION1, this.version1);
                Connector.getConnection().putToDb(database, docid, jDoc.toJSONString());
            }
        }
    } catch (Exception e) {
        System.out.println(e.getMessage());
        throw new MMLException(e);
    }
}

From source file:com.official.wears.site.UploadServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException {
    // Check that we have a file upload request
    isMultipart = ServletFileUpload.isMultipartContent(request);
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    if (!isMultipart) {
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<p>No file uploaded</p>");
        out.println("</body>");
        out.println("</html>");
        return;//from   ww w . j  a  v  a  2 s.co  m
    }
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(maxMemSize);
    // Location to save data that is larger than maxMemSize.
    factory.setRepository(new File("c:\\temp"));

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum file size to be uploaded.
    upload.setSizeMax(maxFileSize);

    try {
        // Parse the request to get file items.
        List fileItems = upload.parseRequest(request);

        // Process the uploaded file items
        Iterator i = fileItems.iterator();

        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");
        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            if (!fi.isFormField()) {
                // Get the uploaded file parameters
                String fieldName = fi.getFieldName();
                String fileName = fi.getName();
                String contentType = fi.getContentType();
                boolean isInMemory = fi.isInMemory();
                long sizeInBytes = fi.getSize();
                // Write the file
                if (fileName.lastIndexOf("\\") >= 0) {
                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
                } else {
                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));
                }
                fi.write(file);
                out.println("Uploaded Filename: " + fileName + "<br>");
            }
        }
        out.println("</body>");
        out.println("</html>");
    } catch (Exception ex) {
        System.out.println(ex);
    }
}

From source file:com.fatih.edu.tr.NewTaskServlet.java

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

    // Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (!isMultipart) {
        return;/* w  w w .j  ava  2  s . c  o m*/
    }

    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();

    // Sets the size threshold beyond which files are written directly to
    // disk.
    factory.setSizeThreshold(MAX_MEMORY_SIZE);

    // Sets the directory used to temporarily store files that are larger
    // than the configured size threshold. We use temporary directory for
    // java
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    // constructs the folder where uploaded file will be stored
    String uploadFolder = getServletContext().getRealPath("") + File.separator + DATA_DIRECTORY;

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

    // Set overall request size constraint
    upload.setSizeMax(MAX_REQUEST_SIZE);

    TaskDao taskDao = new TaskDao();
    String title = "";
    String description = "";
    String due_date = "";
    String fileName = "";
    String filePath = "";
    //taskDao.addTask(title, description, due_date, "testfile","testdizi",1);

    try {
        // Parse the request
        List items = upload.parseRequest(request);
        Iterator iter = items.iterator();
        while (iter.hasNext()) {

            FileItem item = (FileItem) iter.next();

            if (!item.isFormField()) {
                fileName = new File(item.getName()).getName();
                filePath = uploadFolder + File.separator + fileName;
                File uploadedFile = new File(filePath);
                System.out.println(filePath);
                item.write(uploadedFile);
            } else {
                String fieldname = item.getFieldName();
                String fieldvalue = item.getString();
                if (fieldname.equals("title")) {
                    title = item.getString();
                } else if (fieldname.equals("description")) {
                    description = item.getString();

                } else if (fieldname.equals("due_date")) {
                    due_date = item.getString();
                } else {
                    System.out.println("Something goes wrong in form");
                }
            }

        }
        taskDao.addTask(title, description, due_date, fileName, filePath, 1);
        // displays done.jsp page after upload finished
        getServletContext().getRequestDispatcher("/done.jsp").forward(request, response);

    } catch (FileUploadException ex) {
        throw new ServletException(ex);
    } catch (Exception ex) {
        throw new ServletException(ex);
    }

}

From source file:cdc.util.Upload.java

public boolean anexos(HttpServletRequest request) throws Exception {
    request.setCharacterEncoding("ISO-8859-1");
    if (ServletFileUpload.isMultipartContent(request)) {
        int cont = 0;
        ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
        List fileItemsList = null;
        try {//from   w  ww. ja  v  a  2s  .c  om
            fileItemsList = servletFileUpload.parseRequest(request);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        String optionalFileName = "";
        FileItem fileItem = null;
        Iterator it = fileItemsList.iterator();
        do {
            //cont++;
            FileItem fileItemTemp = (FileItem) it.next();
            if (fileItemTemp.isFormField()) {
                if (fileItemTemp.getFieldName().equals("file")) {
                    optionalFileName = fileItemTemp.getString();
                }
                parametros.put(fileItemTemp.getFieldName(), fileItemTemp.getString());
            } else {
                fileItem = fileItemTemp;
            }
            if (cont != (fileItemsList.size())) {
                if (fileItem != null) {
                    String fileName = fileItem.getName();
                    if (fileItem.getSize() > 0) {
                        if (optionalFileName.trim().equals("")) {
                            fileName = FilenameUtils.getName(fileName);
                        } else {
                            fileName = optionalFileName;
                        }
                        String dirName = request.getServletContext().getRealPath(pasta);
                        File saveTo = new File(dirName + "/" + fileName);
                        //verificando se a pasta existe. Caso contrrio, criar ela
                        File pasta = new File(dirName);
                        if (!pasta.exists())
                            pasta.mkdirs();//criando a pasta

                        parametros.put("foto", fileName);

                        try {
                            fileItem.write(saveTo);//Escrevendo o arquivo temporrio no diretrio correto
                        } catch (Exception e) {
                        }
                    }
                }
            }
            cont++;
        } while (it.hasNext());
        return true;
    } else {
        return false;
    }
}

From source file:com.pamarin.servlet.uploadfile.UploadFileServet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    LOG.log(Level.INFO, "uploaded");

    try {//from   w  w w.  ja  v a2s  . co  m
        if (!ServletFileUpload.isMultipartContent(request)) {
            return;
        }

        LOG.log(Level.INFO, "is multipart");
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(maxMemSize);
        factory.setRepository(new File("c:\\temp"));
        //
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(maxFileSize);

        List<FileItem> fileItems = upload.parseRequest(request);
        Iterator<FileItem> iterator = fileItems.iterator();

        LOG.log(Level.INFO, "file size --> {0}", fileItems.size());
        while (iterator.hasNext()) {
            FileItem item = iterator.next();
            //if (!item.isFormField()) {
            LOG.log(Level.INFO, "content type --> {0}", item.getContentType());
            LOG.log(Level.INFO, "name --> {0}", item.getName());
            LOG.log(Level.INFO, "field name --> {0}", item.getFieldName());
            LOG.log(Level.INFO, "string --> {0}", item.getString());

            item.write(new File("c:\\temp", UUID.randomUUID().toString() + ".png"));
            //}
        }
    } catch (FileUploadException ex) {
        LOG.log(Level.WARNING, ex.getMessage());
    } catch (Exception ex) {
        LOG.log(Level.WARNING, ex.getMessage());
    }
}

From source file:hu.ptemik.gallery.servlets.UploadServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpSession session = request.getSession(false);
    User user = (User) session.getAttribute("user");
    String uploadFolder = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;

    if (ServletFileUpload.isMultipartContent(request) && user != null) {
        try {//w w w.j  a  v  a2  s.co  m
            List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
            Picture pic = new Picture();
            File uploadedFile = null;

            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    String fileName = new File(item.getName()).getName();
                    String filePath = uploadFolder + File.separator + fileName;
                    String relativePath = UPLOAD_DIRECTORY + "/" + fileName;

                    uploadedFile = new File(filePath);
                    item.write(uploadedFile);

                    pic.setUrl(relativePath);
                } else {
                    if (item.getFieldName().equals("title")) {
                        pic.setTitle(item.getString());
                    } else if (item.getFieldName().equals("description")) {
                        pic.setDescription(item.getString());
                    }
                }
            }

            if (Controller.newPicture(pic, user)) {
                request.setAttribute("successMessage", "A fjl feltltse sikerlt!");
            } else {
                FileUtils.deleteQuietly(uploadedFile);
                throw new Exception();
            }
        } catch (FileNotFoundException ex) {
            request.setAttribute("errorMessage", "Hinyzik a fjl!");
        } catch (Exception ex) {
            request.setAttribute("errorMessage", "Hiba a fjl feltltse sorn!");
        }
    } else {
        request.setAttribute("errorMessage", "Form hiba");
    }

    request.getRequestDispatcher("upload.jsp").forward(request, response);
}

From source file:com.github.ikidou.handler.FormHandler.java

@Override
public Object handle(Request request, Response response) throws Exception {
    Map<String, Object> result = new HashMap<>();

    addCustomHeaders(request, result);//ww  w  . j  a va2  s  .  c  o m

    addQueryParams(request, result);

    if (ServletFileUpload.isMultipartContent(request.raw())) {
        ServletFileUpload fileUpload = new ServletFileUpload(new DiskFileItemFactory(8, new File("./Data")));
        List<FileItem> fileItems = fileUpload.parseRequest(request.raw());
        List<FileEntity> fileEntities = getFileEntities(result, fileItems);
        if (!fileEntities.isEmpty())
            result.put("_files", fileEntities);
    }

    return result;
}

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  .  j a v  a  2s  . 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:com.google.caja.ancillary.servlet.UploadPage.java

static void doUpload(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    // Process the uploaded items
    List<ObjectConstructor> uploads = Lists.newArrayList();

    if (ServletFileUpload.isMultipartContent(req)) {
        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();

        int maxUploadSizeBytes = 1 << 18;
        factory.setSizeThreshold(maxUploadSizeBytes); // In-memory threshold
        factory.setRepository(new File("/dev/null")); // Do not store on disk
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(maxUploadSizeBytes);

        writeHeader(resp);// www  .j  av a  2  s  . c o m

        // Parse the request
        List<?> items;
        try {
            items = upload.parseRequest(req);
        } catch (FileUploadException ex) {
            ex.printStackTrace();
            resp.getWriter().write(Nodes.encode(ex.getMessage()));
            return;
        }

        for (Object fileItemObj : items) {
            FileItem item = (FileItem) fileItemObj; // Written for pre-generic java.
            if (!item.isFormField()) { // Then is a file
                FilePosition unk = FilePosition.UNKNOWN;
                String ct = item.getContentType();
                uploads.add((ObjectConstructor) QuasiBuilder.substV("({ i: @i, ip: @ip, it: @it? })", "i",
                        StringLiteral.valueOf(unk, item.getString()), "ip",
                        StringLiteral.valueOf(unk, item.getName()), "it",
                        ct != null ? StringLiteral.valueOf(unk, ct) : null));
            }
        }
    } else if (req.getParameter("url") != null) {
        List<URI> toFetch = Lists.newArrayList();
        boolean failed = false;
        for (String value : req.getParameterValues("url")) {
            try {
                toFetch.add(new URI(value));
            } catch (URISyntaxException ex) {
                if (!failed) {
                    failed = true;
                    resp.setStatus(500);
                    resp.setContentType("text/html;charset=UTF-8");
                }
                resp.getWriter().write("<p>Bad URI: " + Nodes.encode(ex.getMessage()));
            }
        }
        if (failed) {
            return;
        }
        writeHeader(resp);
        FilePosition unk = FilePosition.UNKNOWN;
        for (URI uri : toFetch) {
            try {
                Content c = UriFetcher.fetch(uri);
                if (c.isText()) {
                    uploads.add((ObjectConstructor) QuasiBuilder.substV("({ i: @i, ip: @ip, it: @it? })", "i",
                            StringLiteral.valueOf(unk, c.getText()), "ip",
                            StringLiteral.valueOf(unk, uri.toString()), "it",
                            StringLiteral.valueOf(unk, c.type.mimeType)));
                }
            } catch (IOException ex) {
                resp.getWriter()
                        .write("<p>" + Nodes.encode("Failed to fetch URI: " + uri + " : " + ex.getMessage()));
            }
        }
    } else {
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        resp.getWriter().write("Content not multipart");
        return;
    }

    Expression notifyParent = (Expression) QuasiBuilder.substV(
            "window.parent.uploaded([@uploads*], window.name)", "uploads", new ParseTreeNodeContainer(uploads));
    StringBuilder jsBuf = new StringBuilder();
    RenderContext rc = new RenderContext(new JsMinimalPrinter(new Concatenator(jsBuf))).withEmbeddable(true);
    notifyParent.render(rc);
    rc.getOut().noMoreTokens();

    HtmlQuasiBuilder b = HtmlQuasiBuilder.getBuilder(DomParser.makeDocument(null, null));

    Writer out = resp.getWriter();
    out.write(Nodes.render(b.substV("<script>@js</script>", "js", jsBuf.toString())));
}

From source file:calliope.handler.post.AeseTextImportHandler.java

public void handle(HttpServletRequest request, HttpServletResponse response, String urn) throws AeseException {
    try {/*from  w  w w  . ja  v  a 2s.co m*/
        if (ServletFileUpload.isMultipartContent(request)) {
            StringBuilder sb = new StringBuilder();
            // Check that we have a file upload request
            // Create a factory for disk-based file items
            FileItemFactory factory = new DiskFileItemFactory();
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            String log = "";
            sb.append("<html><body>");
            // 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) {
                        sb.append("<p>form field: ");
                        sb.append(fieldName);
                        sb.append("</p>");
                    }
                } else if (item.getName().length() > 0) {
                    String fieldName = item.getFieldName();
                    if (fieldName != null) {
                        sb.append("<p>file field: ");
                        sb.append(fieldName);
                        sb.append("</p>");
                    }
                }
            }
            sb.append("</body></html>");
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().println(sb.toString());
        }
    } catch (Exception e) {
        throw new AeseException(e);
    }
}