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:ee.jaaaar.dreamestate.core.StreamingMultipartResolver.java

@Override
public boolean isMultipart(HttpServletRequest request) {
    return ServletFileUpload.isMultipartContent(request);
}

From source file:com.emlak.servlets.UploadFile.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   w  ww .ja  v  a 2 s. co  m
 *
 * @param request servlet request
 * @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");
    System.out.println("Buraya Geliyorum");
    int evid = Integer.parseInt(request.getParameter("evida"));

    System.out.println(evid);
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    String name = null;
    // process only if it is multipart content
    if (isMultipart) {
        // Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            // Parse the request
            List<FileItem> multiparts = upload.parseRequest(request);

            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    name = new File(item.getName()).getName();
                    item.write(new File(UPLOAD_DIRECTORY + File.separator + name));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    boolean a = EvResimKaydet.resimKaydet(evid, name);
    System.out.println("name :" + UPLOAD_DIRECTORY + File.separator + name + " " + a);
}

From source file:kg12.Ex12_2.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*  www . jav a 2s. co m*/
 *
 * @param request servlet request
 * @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();

    try {
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet Ex12_2</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>???</h1>");

        // multipart/form-data ??
        if (ServletFileUpload.isMultipartContent(request)) {
            out.println("???<br>");
        } else {
            out.println("?????<br>");
            out.close();
            return;
        }

        // ServletFileUpload??
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload sfu = new ServletFileUpload(factory);

        // ???
        int fileSizeMax = 1024000;
        factory.setSizeThreshold(1024);
        sfu.setSizeMax(fileSizeMax);
        sfu.setHeaderEncoding("UTF-8");

        // ?
        String format = "%s:%s<br>%n";

        // ???????
        FileItemIterator fileIt = sfu.getItemIterator(request);

        while (fileIt.hasNext()) {
            FileItemStream item = fileIt.next();

            if (item.isFormField()) {
                //
                out.print("<br>??<br>");
                out.printf(format, "??", item.getFieldName());
                InputStream is = item.openStream();

                // ? byte ??
                byte[] b = new byte[255];

                // byte? b ????
                is.read(b, 0, b.length);

                // byte? b ? "UTF-8" ??String??? result ?
                String result = new String(b, "UTF-8");
                out.printf(format, "", result);
            } else {
                //
                out.print("<br>??<br>");
                out.printf(format, "??", item.getName());
                InputStream is = item.openStream();

                String fileName = item.getName();
                int len = 0;
                byte[] buffer = new byte[fileSizeMax];

                FileOutputStream fos = new FileOutputStream(
                        "D:\\NetBeansProjects\\ap2_www\\web\\kg12\\" + fileName);
                try {
                    while ((len = is.read(buffer)) > 0) {
                        fos.write(buffer, 0, len);
                    }
                } finally {
                    fos.close();
                }

            }
        }
        out.println("</body>");
        out.println("</html>");
    } catch (FileUploadException e) {
        out.println(e + "<br>");
        throw new ServletException(e);
    } catch (Exception e) {
        out.println(e + "<br>");
        throw new ServletException(e);
    } finally {
        out.close();
    }
}

From source file:com.boha.minisass.gate.PhotoServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   w ww.j a  v a 2 s.  c  o  m*/
 *
 * @param request servlet request
 * @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("application/json;charset=UTF-8");
    PrintWriter out = response.getWriter();
    long start = System.currentTimeMillis();

    ResponseDTO ur = new ResponseDTO();
    String json;
    Gson gson = new Gson();
    try {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart) {
            ur = photoUtil.downloadPhotos(request, dataUtil, platformUtil);
        } else {
            RequestDTO dto = getRequest(gson, request);
            switch (dto.getRequestType()) {

            }

        }

    } catch (FileUploadException ex) {
        logger.log(Level.SEVERE, "File upload FAILED!!", ex);
        ur.setStatusCode(111);
        ur.setMessage("Error. Unable to download file(s) sent. Contact Support");

    } catch (Exception e) {
        logger.log(Level.SEVERE, "Servlet file upload FAILED, check it out!", e);
        ur.setStatusCode(113);
        ur.setMessage("Error. Generic server exception");

    } finally {
        json = gson.toJson(ur);
        out.println(json);
        out.close();
        long end = System.currentTimeMillis();
        logger.log(Level.INFO, "PhotoServlet done, elapsed: {0} seconds", getElapsed(start, end));
    }
}

From source file:com.radio.svc.controllers.admin.AddFeatureSSDController.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    //To change body of generated methods, choose Tools | Templates.
    String[] ssdFeatures = null;/*from  w w  w.ja v  a  2s .co  m*/
    FileItem ssdFeatureFile = null;
    String songName = null;

    if (ServletFileUpload.isMultipartContent(request)) {

        try {
            List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
            for (FileItem item : multiparts) {
                if (!item.isFormField()) {

                    if (item.getFieldName().equals("ssdFeatureUpload")) {
                        ssdFeatureFile = item;

                    }

                } else {
                    if (item.getFieldName().equals("songname")) {
                        songName = item.getString();
                        //System.out.println( "Album Name  " + item.getString() );
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    ModelAndView model;
    model = new ModelAndView("/admin/featureSSDAdmin");
    model.addObject("controller", "addfeaturessd");
    featureSSDServiceProvider.addNewFeatureSSD(songName, ssdFeatureFile);
    model.addObject("msg", "success");

    return model;

}

From source file:com.bigdata.rockstor.console.UploadServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    if (!ServletFileUpload.isMultipartContent(req)) {
        LOG.error("It is not a MultipartContent, return error.");
        resp.sendError(500, "It is not a MultipartContent, return error.");
        return;//from ww w .  j  ava 2 s  . c  om
    }

    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setFileSizeMax(1024 * 1024 * 512);
    List<FileItem> fileItems = null;
    try {
        fileItems = upload.parseRequest(req);
        LOG.info("parse requeset success : items num : " + fileItems.size());
    } catch (FileUploadException e) {
        LOG.error("parse requeset failed !");
        resp.sendError(500, "parse requeset failed !");
        return;
    }

    HashMap<String, String> headMap = new HashMap<String, String>();
    FileItem theFile = null;
    long size = -1;
    URI uri = null;

    Iterator<FileItem> iter = fileItems.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();

        if (item.isFormField()) {
            String name = item.getFieldName();
            String value = null;
            try {
                value = item.getString("UTF-8").trim();
            } catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
            }
            LOG.info("Parse head info : " + name + " -- " + value);
            if (name.equals("ObjName")) {
                try {
                    uri = new URI(value);
                } catch (URISyntaxException e) {
                    LOG.info("Parse uri info error : " + value);
                    uri = null;
                }
            } else if (name.equals("ObjSize")) {
                try {
                    size = Long.parseLong(value);
                } catch (Exception e) {
                    LOG.error("Parse objSize error : " + value);
                }
            } else {
                headMap.put(name, value);
            }
        } else {
            theFile = item;
        }
    }

    if (size == -1 || uri == null || theFile == null || headMap.size() == 0) {
        LOG.error("Parse upload info error : size==-1 || uri == null || theFile == null || headMap.size()==0");
        resp.sendError(500,
                "Parse upload info error : size==-1 || uri == null || theFile == null || headMap.size()==0");
        return;
    }

    HttpPut put = new HttpPut();
    put.setURI(uri);
    for (Map.Entry<String, String> e : headMap.entrySet()) {
        if ("Filename".equals(e.getKey()))
            continue;
        put.setHeader(e.getKey(), e.getValue());
    }
    put.setEntity(new InputStreamEntity(theFile.getInputStream(), size));
    DefaultHttpClient client = new DefaultHttpClient();
    HttpResponse response = client.execute(put);
    if (200 != response.getStatusLine().getStatusCode()) {
        LOG.error("Put object error : " + response.getStatusLine().getStatusCode() + " : "
                + response.getStatusLine().getReasonPhrase());
        resp.sendError(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase());
        return;
    }
    LOG.info("Put object OK : " + uri);
    response.setStatusCode(200);
}

From source file:controller.uploadPergunta9.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from ww  w  . ja va  2 s. c  o  m
 *
 * @param request servlet request
 * @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 {

    String idLocal = (String) request.getParameter("idLocal");
    String idModelo = (String) request.getParameter("idModelo");
    String expressaoModelo = (String) request.getParameter("expressaoModelo");
    String nomeAutorModelo = (String) request.getParameter("nomeAutorModelo");
    String equacaoAjustada = (String) request.getParameter("equacaoAjustada");
    String idEquacaoAjustada = (String) request.getParameter("idEquacaoAjustada");

    String name = "";
    //process only if its multipart content
    if (ServletFileUpload.isMultipartContent(request)) {
        try {
            List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    name = new File(item.getName()).getName();
                    //                        item.write( new File(UPLOAD_DIRECTORY + File.separator + name));
                    item.write(new File(AbsolutePath + File.separator + name));
                }
            }

            //File uploaded successfully
            request.setAttribute("message", "File Uploaded Successfully");
        } catch (Exception ex) {
            request.setAttribute("message", "File Upload Failed due to " + ex);
        }

    } else {
        request.setAttribute("message", "Sorry this Servlet only handles file upload request");
    }
    equacaoAjustada = equacaoAjustada.replace("+", "%2B");
    expressaoModelo = expressaoModelo.replace("+", "%2B");
    RequestDispatcher view = getServletContext()
            .getRequestDispatcher("/novoLocalPergunta9?id=" + idLocal + "&nomeArquivo=" + name + "&idModelo="
                    + idModelo + "&equacaoAjustada=" + equacaoAjustada + "&expressaoModelo=" + expressaoModelo
                    + "&nomeAutorModelo=" + nomeAutorModelo + "&idEquacaoAjustada=" + idEquacaoAjustada);
    view.forward(request, response);

    //        request.getRequestDispatcher("/novoLocalPergunta3?id="+idLocal+"&fupload=1&nomeArquivo="+name).forward(request, response);
    // request.getRequestDispatcher("/novoLocalPergunta4?id="+idLocal+"&nomeArquivo="+name).forward(request, response);

}

From source file:Control.HandleTest.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  ww  w  .  ja v a  2 s .c  om*/
 *
 * @param request servlet request
 * @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()) {
        /* TODO output your page here. You may use following sample code. */
        String path = getClass().getResource("/").getPath();

        if (Paths.path == null) {
            File file = new File(path + "test.html");
            path = file.getParent();
            File file1 = new File(path + "test1.html");
            path = file1.getParent();
            File file2 = new File(path + "test1.html");
            path = file2.getParent();
            Paths.path = path;
        } else {
            path = Paths.path;
        }
        String name;
        if (ServletFileUpload.isMultipartContent(request)) {
            List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    name = new File(item.getName()).getName();
                    // temp.logoImage = Paths.logoPath + name;
                    String FilePath = path + Paths.logoPathStore + name;
                    item.write(new File(FilePath));
                }
            }
        }
    } catch (Exception e) {

    }
}

From source file:edu.iastate.airl.semtus.server.UploadServiceController.java

public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    // process only multipart requests
    if (ServletFileUpload.isMultipartContent(req)) {

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

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

        // Parse the request
        try {/*from   www. java  2 s.co  m*/
            List<FileItem> items = upload.parseRequest(req);
            for (FileItem item : items) {
                // process only file upload - discard other form item types
                if (item.isFormField())
                    continue;

                String fileName = item.getName();
                // get only the file name not whole path
                if (fileName != null) {
                    fileName = FilenameUtils.getName(fileName);
                }

                File uploadedFile = new File(Utils.UPLOAD_DIRECTORY, fileName);

                // first clean-up the folder; we want no clutter on the server :-)
                String[] ls = new File(Utils.UPLOAD_DIRECTORY).list();

                for (int idx = 0; idx < ls.length; idx++) {

                    File file = new File(Utils.UPLOAD_DIRECTORY, ls[idx]);
                    file.delete();
                }

                if (uploadedFile.createNewFile()) {

                    item.write(uploadedFile);
                    resp.setStatus(HttpServletResponse.SC_CREATED);
                    resp.getWriter().print("The file was created successfully.");
                    resp.flushBuffer();

                } else {

                    throw new IOException("The file already exists in repository.");
                }
            }
        } catch (Exception e) {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while creating the file : " + e.getMessage());
        }

    } else {
        resp.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
                "Request contents type is not supported by the servlet.");
    }
}

From source file:com.controller.RecipeImage.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  w ww  .j a va 2s . c o  m
 *
 * @param request servlet request
 * @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");

    //retrieving the path to store image from web.xml
    filePath = getServletContext().getInitParameter("recipeImageStorePath");

    //retrieving the path to display image from web.xml
    fileDisplay = getServletContext().getInitParameter("recipeImageDisplayPath");

    // 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;
    }
    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>");
        out.println("1");
        while (i.hasNext()) {
            out.println("2");
            FileItem fi = (FileItem) i.next();
            if (!fi.isFormField()) {
                // Get the uploaded file parameters
                String fieldName = fi.getFieldName();
                fileName = fi.getName();
                fileName = randomString(fileName);
                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>" + filePath);
            } else {
                out.println("No file");
            }
        }
        out.println("</body>");
        out.println("</html>");

        RecipeBean recipeBean = new RecipeBean();
        RecipeDAO recipeDAO = new RecipeDAO();

        String image = fileDisplay + "" + fileName;
        out.println(image);

        HttpSession session = request.getSession();
        String recipeId = (String) session.getAttribute("recipeId");
        session.removeAttribute("recipeId");
        recipeDAO.addImage(recipeId, image);

        response.sendRedirect("Home");

    } catch (Exception ex) {
        System.out.println(ex);
    }
}