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:mx.edu.ittepic.proyectofinal.servlets.UploadFile.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from   www.j a  v a 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
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    // 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()) {
                    String name = new File(item.getName()).getName();
                    item.write(new File(UPLOAD_DIRECTORY + File.separator + name));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

From source file:com.woonoz.proxy.servlet.HttpPostRequestHandler.java

private HttpEntity createHttpEntity(HttpServletRequest request, HttpPost httpPost)
        throws FileUploadException, IOException {
    if (ServletFileUpload.isMultipartContent(request)) {
        return createMultipartEntity(request, httpPost);
    } else {/*  ww w.  j  a  va 2s . c  om*/
        return new BufferedHttpEntity(
                new InputStreamEntity(request.getInputStream(), request.getContentLength()));
    }
}

From source file:edu.ucla.loni.server.Upload.java

public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    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);

        try {//from w  w  w  .jav  a2s  .c  om
            @SuppressWarnings("unchecked")
            List<FileItem> items = upload.parseRequest(req);

            // Go through the items and get the root and package
            String rootPath = "";
            String packageName = "";

            for (FileItem item : items) {
                if (item.isFormField()) {
                    if (item.getFieldName().equals("root")) {
                        rootPath = item.getString();
                    } else if (item.getFieldName().equals("packageName")) {
                        packageName = item.getString();
                    }
                }
            }

            if (rootPath.equals("")) {
                res.getWriter().println("error :: Root directory has not been found.");
                return;
            }

            Directory root = Database.selectDirectory(rootPath);

            // Go through items and process urls and files
            for (FileItem item : items) {
                // Uploaded File
                if (item.isFormField() == false) {
                    String filename = item.getName();
                    ;
                    if (filename.equals("") == true)
                        continue;
                    try {
                        InputStream in = item.getInputStream();
                        //determine if it is pipefile or zipfile
                        //if it is pipefile => feed directly to writeFile function
                        //otherwise, uncompresse it first and then one-by-one feed to writeFile
                        if (filename.endsWith(".zip")) {
                            ZipInputStream zip = new ZipInputStream(in);
                            ZipEntry entry = zip.getNextEntry();
                            while (entry != null) {
                                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                                if (baos != null) {
                                    byte[] arr = new byte[4096];
                                    int index = 0;
                                    while ((index = zip.read(arr, 0, 4096)) != -1) {
                                        baos.write(arr, 0, index);
                                    }
                                }
                                InputStream is = new ByteArrayInputStream(baos.toByteArray());
                                writeFile(root, packageName, is);
                                entry = zip.getNextEntry();
                            }
                            zip.close();
                        } else {
                            writeFile(root, packageName, in);

                        }

                        in.close();
                    } catch (Exception e) {
                        res.getWriter().println("Failed to upload " + filename + ". " + e.getMessage());
                    }
                }
                // URLs               
                if (item.isFormField() && item.getFieldName().equals("urls")
                        && item.getString().equals("") == false) {
                    String urlListAsStr = item.getString();
                    String[] urlList = urlListAsStr.split("\n");

                    for (String urlStr : urlList) {
                        try {
                            URL url = new URL(urlStr);
                            URLConnection urlc = url.openConnection();

                            InputStream in = urlc.getInputStream();

                            writeFile(root, packageName, in);

                            in.close();
                        } catch (Exception e) {
                            res.getWriter().println("Failed to upload " + urlStr);
                            return;
                        }
                    }
                }
            }
        } catch (Exception e) {
            res.getWriter().println("Error occurred while creating file. Error Message : " + e.getMessage());
        }
    }
}

From source file:isl.FIMS.servlet.imports.ImportVocabulary.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    this.initVars(request);
    String username = getUsername(request);

    Config conf = new Config("AdminVoc");

    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    StringBuilder xml = new StringBuilder(
            this.xmlStart(this.topmenu, username, this.pageTitle, this.lang, "", request));
    String file = request.getParameter("file");

    if (ServletFileUpload.isMultipartContent(request)) {
        // configures some settings
        String filePath = this.export_import_Folder;
        java.util.Date date = new java.util.Date();
        Timestamp t = new Timestamp(date.getTime());
        String currentDir = filePath + t.toString().replaceAll(":", "");
        File saveDir = new File(currentDir);
        if (!saveDir.exists()) {
            saveDir.mkdir();//from  w w  w . ja  va2s.  c om
        }
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD);
        factory.setRepository(saveDir);

        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(REQUEST_SIZE);
        // constructs the directory path to store upload file
        String uploadPath = currentDir;

        try {
            // parses the request's content to extract file data
            List formItems = upload.parseRequest(request);
            Iterator iter = formItems.iterator();
            // iterates over form's fields
            File storeFile = null;
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                // processes only fields that are not form fields
                if (!item.isFormField()) {
                    String fileName = new File(item.getName()).getName();
                    filePath = uploadPath + File.separator + fileName;
                    storeFile = new File(filePath);
                    // saves the file on disk
                    item.write(storeFile);
                }
            }
            ArrayList<String> content = Utils.readFile(storeFile);
            DMSConfig vocConf = new DMSConfig(this.DBURI, this.systemDbCollection + "Vocabulary/", this.DBuser,
                    this.DBpassword);
            Vocabulary voc = new Vocabulary(file, this.lang, vocConf);
            String[] terms = voc.termValues();

            for (int i = 0; i < content.size(); i++) {
                String addTerm = content.get(i);
                if (!Arrays.asList(terms).contains(addTerm)) {
                    voc.addTerm(addTerm);
                }

            }
            Utils.deleteDir(currentDir);
            response.sendRedirect("AdminVoc?action=list&file=" + file + "&menuId=AdminVoc");
        } catch (Exception ex) {
        }

    }

    xml.append("<FileName>").append(file).append("</FileName>\n");
    xml.append("<EntityType>").append("AdminVoc").append("</EntityType>\n");

    xml.append(this.xmlEnd());
    String xsl = conf.IMPORT_Vocabulary;
    try {
        XMLTransform xmlTrans = new XMLTransform(xml.toString());
        xmlTrans.transform(out, xsl);
    } catch (DMSException e) {
        e.printStackTrace();
    }
    out.close();
}

From source file:com.pronoiahealth.olhie.server.rest.BookAssetUploadServiceImpl.java

/**
 * Receive an upload book assest//from   w  w w  .jav a 2 s .  co m
 * 
 * @see com.pronoiahealth.olhie.server.rest.BookAssetUploadService#process2(javax.servlet.http.HttpServletRequest)
 */
@Override
@POST
@Path("/upload2")
@Produces("text/html")
@SecureAccess({ SecurityRoleEnum.ADMIN, SecurityRoleEnum.AUTHOR })
public String process2(@Context HttpServletRequest req)
        throws ServletException, IOException, FileUploadException {
    try {
        // Check that we have a file upload request
        boolean isMultipart = ServletFileUpload.isMultipartContent(req);
        if (isMultipart == true) {

            // FileItemFactory fileItemFactory = new FileItemFactory();
            String description = null;
            String descriptionDetail = null;
            String hoursOfWorkStr = null;
            String bookId = null;
            String action = null;
            String dataType = null;
            String contentType = null;
            //String data = null;
            byte[] bytes = null;
            String fileName = null;
            long size = 0;
            ServletFileUpload fileUpload = new ServletFileUpload();
            fileUpload.setSizeMax(FILE_SIZE_LIMIT);
            FileItemIterator iter = fileUpload.getItemIterator(req);
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                InputStream stream = item.openStream();
                if (item.isFormField()) {
                    // description
                    if (item.getFieldName().equals("description")) {
                        description = Streams.asString(stream);
                    }

                    // detail
                    if (item.getFieldName().equals("descriptionDetail")) {
                        descriptionDetail = Streams.asString(stream);
                    }

                    // Work hours
                    if (item.getFieldName().equals("hoursOfWork")) {
                        hoursOfWorkStr = Streams.asString(stream);
                    }

                    // BookId
                    if (item.getFieldName().equals("bookId")) {
                        bookId = Streams.asString(stream);
                    }

                    // action
                    if (item.getFieldName().equals("action")) {
                        action = Streams.asString(stream);
                    }

                    // datatype
                    if (item.getFieldName().equals("dataType")) {
                        dataType = Streams.asString(stream);
                    }

                } else {
                    if (item != null) {
                        contentType = item.getContentType();
                        fileName = item.getName();
                        item.openStream();
                        InputStream in = item.openStream();
                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        IOUtils.copy(in, bos);
                        bytes = bos.toByteArray();
                        size = bytes.length;
                    }
                }
            }

            // convert the hoursOfWork
            int hoursOfWork = 0;
            if (hoursOfWorkStr != null) {
                try {
                    hoursOfWork = Integer.parseInt(hoursOfWorkStr);
                } catch (Exception e) {
                    log.log(Level.WARNING, "Could not conver " + hoursOfWorkStr
                            + " to an int in BookAssetUploadServiceImpl. Converting to 0.");
                    hoursOfWork = 0;
                }
            }

            // Verify that the session user is the author or co-author of
            // the book. They would be the only ones who could add to the
            // book.
            String userId = userToken.getUserId();
            boolean isAuthor = bookDAO.isUserAuthorOrCoauthorOfBook(userId, bookId);
            if (isAuthor == false) {
                throw new Exception("The user " + userId + " is not the author or co-author of the book.");
            }

            // Add to the database
            bookDAO.addUpdateBookassetBytes(description, descriptionDetail, bookId, contentType,
                    BookAssetDataType.valueOf(dataType).toString(), bytes, action, fileName, null, null, size,
                    hoursOfWork, userId);

            // Tell Solr about the update
            queueBookEvent.fire(new QueueBookEvent(bookId, userId));
        }
        return "OK";
    } catch (Exception e) {
        log.log(Level.SEVERE, "Throwing servlet exception for unhandled exception", e);
        // return "ERROR:\n" + e.getMessage();

        if (e instanceof FileUploadException) {
            throw (FileUploadException) e;
        } else {
            throw new FileUploadException(e.getMessage());
        }
    }
}

From source file:com.glaf.base.utils.upload.FileUploadBackGroundServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        processFileUpload(request, response);
    } else {/*from  www . j  a va2s . c om*/
        request.setCharacterEncoding("UTF-8");

        if (request.getParameter("uploadStatus") != null) {
            responseStatusQuery(request, response);
        }
        if (request.getParameter("cancelUpload") != null) {
            processCancelFileUpload(request, response);
        }
        if (request.getParameter("download") != null) {
            processDownload(request, response);
        }

    }
}

From source file:cn.clxy.studio.common.web.multipart.GMultipartResolver.java

/**
 * Returns true if the request has multipart.
 *//*from www . j  av  a  2 s .c o m*/
public boolean isMultipart(HttpServletRequest request) {
    return (request != null && ServletFileUpload.isMultipartContent(request));
}

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;//from   www. jav  a2  s.  co 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:edu.temple.cis3238.wiki.ui.servlets.UploaderServlet.java

/**
 * Processes requests for HTTP  <code>POST</code> method.
 *
 * @param request  servlet request// w  ww.  j a v a  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");
    try (PrintWriter out = response.getWriter()) {

        // checks if the request actually contains upload file
        if (!ServletFileUpload.isMultipartContent(request)) {
            // if not, we stop here
            PrintWriter writer = response.getWriter();
            writer.println("Error: Form must be  enctype = multipart/form-data.");
            writer.flush();
            setSuccess(false);
            return;
        }

        // configures upload settings
        DiskFileItemFactory factory = new DiskFileItemFactory();

        factory.setSizeThreshold(MEMORY_THRESHOLD);

        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setFileSizeMax(MAX_FILE_SIZE);
        upload.setSizeMax(MAX_REQUEST_SIZE);
        if (request.getSession() != null && request.getSession().getAttribute("topicCollection") != null) {
            try {
                collection = (TopicCollection) request.getSession().getAttribute("topicCollection");
                setTopic(collection.getCurrentTopic());
                setTopicID(getTopic().getTopicID() + "");
            } catch (Exception e) {
                e.printStackTrace();
                if (getTopic() == null) {
                    try {
                        setTopicID(request.getSession().getAttribute("topicID").toString());
                        setTopic(new TopicVOBuilder().setTopicID(Integer.parseInt(getTopicID())).build());
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            }
        } else {
            setTopicID("none");
        }

        String uploadPath = FileUtils.makeDir(getServletContext(), UPLOAD_DIRECTORY, getTopic());
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();

        }

        try {
            // parses the request's content to extract file data
            @SuppressWarnings("unchecked")
            List<FileItem> formItems = upload.parseRequest(request);
            String fileName = "";

            if (formItems != null && formItems.size() > 0) {
                // iterates over form's fields
                for (FileItem item : formItems) {

                    if (!item.isFormField()) {
                        fileName = new File(item.getName()).getName();
                        String filePath = uploadPath + File.separator + fileName;
                        System.out.println(filePath);
                        File storeFile = new File(filePath);

                        if (FileUtils.checkFileExtension(storeFile.getName().toLowerCase(), null)) {
                            item.write(storeFile);
                            request.setAttribute("sourceFile", fileName);
                            System.out.println("----------------------------");
                            System.out.println("FILENAME is :" + fileName);
                            System.out.println("----------------------------");
                            request.setAttribute("topicID", StringUtils.toS(getTopicID()));
                            setStatus(request, true, "Success: Topic " + StringUtils.toS(getTopicID())
                                    + " has saved file " + fileName + ". Upload has been done successfully!");
                        } else {
                            setStatus(request, false, "Exception: Invalid file extension");
                        }
                    }
                }
            } else {
                setStatus(request, false, "Exception: No valid file(s)");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            setStatus(request, false,
                    "Exception: " + StringUtils.coalesce(ex.getMessage(), ex.toString(), "unknown"));
        }
        // redirects client to message page
        getServletContext().getRequestDispatcher("/" + REDIRECT_ON_COMPLETE_PAGE).forward(request, response);
    }
}

From source file:UploadImageEdit.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   w  w w .j a  v  a2s  .  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, FileUploadException, IOException_Exception {
    // Check that we have a file upload request
    PrintWriter writer = response.getWriter();
    String productName = "";
    String description = "";
    String price = "";
    String pictureName = "";
    String productId = "";

    Cookie cookie = null;
    Cookie[] cookies = null;
    String selectedCookie = "";
    // Get an array of Cookies associated with this domain
    cookies = request.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            cookie = cookies[i];
            if (cookie.getName().equals("JuraganDiskon")) {
                selectedCookie = cookie.getValue();
            }
        }
    } else {
        writer.println("<h2>No cookies founds</h2>");
    }

    if (!ServletFileUpload.isMultipartContent(request)) {
        // if not, we stop here

        writer.println("Error: Form must has enctype=multipart/form-data.");
        writer.flush();
        return;
    }

    // configures upload settings
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // sets memory threshold - beyond which files are stored in disk
    factory.setSizeThreshold(MEMORY_THRESHOLD);
    // sets temporary location to store files
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    ServletFileUpload upload = new ServletFileUpload(factory);

    // sets maximum size of upload file
    upload.setFileSizeMax(MAX_FILE_SIZE);

    // sets maximum size of request (include file + form data)
    upload.setSizeMax(MAX_REQUEST_SIZE);

    // constructs the directory path to store upload file
    // this path is relative to application's directory
    String uploadPath = new File(new File(getServletContext().getRealPath("")).getParent()).getParent()
            + "/web/" + UPLOAD_DIRECTORY;

    // creates the directory if it does not exist
    File uploadDir = new File(uploadPath);
    if (!uploadDir.exists()) {
        uploadDir.mkdir();
    }

    try {
        // parses the request's content to extract file data
        @SuppressWarnings("unchecked")
        List<FileItem> formItems = upload.parseRequest(request);

        if (formItems != null && formItems.size() > 0) {
            // iterates over form's fields
            int k = 0;
            for (FileItem item : formItems) {
                // processes only fields that are not form fields
                if (!item.isFormField()) {
                    k++;
                    writer.println("if = " + k);

                    String fileName = new File(item.getName()).getName();
                    pictureName = fileName;
                    String filePath = uploadPath + File.separator + fileName;
                    File storeFile = new File(filePath);

                    // saves the file on disk
                    item.write(storeFile);
                    request.setAttribute("message", "Upload has been done successfully!");
                    writer.println("pictureName = " + pictureName);
                } else {
                    k++;
                    writer.println("else = " + k);

                    // Get the field name
                    String fieldName = item.getName();
                    // Get the field value
                    String value = item.getString();
                    if (k == 0) {

                    } else if (k == 1) {
                        productId = value.trim();
                        writer.println("productId = " + productId);
                    } else if (k == 2) {
                        productName = value;
                        writer.println("productName = " + productName);
                    } else if (k == 3) {
                        description = value;
                        writer.println("description = " + description);
                    } else if (k == 4) {
                        price = value;
                        writer.println("price = " + price);
                    }

                }

            }
        }

    } catch (Exception ex) {
        request.setAttribute("message", "There was an error: " + ex.getMessage());
    }
    String update = editTheProduct(Integer.valueOf(productId), productName, price, description, pictureName,
            selectedCookie);
    writer.println(update);

    //redirects client to message page
    getServletContext().getRequestDispatcher("/yourProduct.jsp").forward(request, response);

}