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

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

Introduction

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

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:httpUtils.HttpUtils.java

/**
 * Parse the httpServletRequest for the file item that was received within a 
 * multipart/form-data POST request//from  w  w w  .j a  va2 s  .  c o m
 * @param httpServletRequest
 * @return the file item
 */
public static DiskFileItem parseRequestForFileItem(HttpServletRequest httpServletRequest) {
    DiskFileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);

    // Parse the request for file
    List<FileItem> items = null;
    try {
        items = upload.parseRequest(httpServletRequest);
    } catch (FileUploadException fue) {
        log.error("Error reading/parsing file", fue);
    }

    if (items.size() != 1) {
        log.debug("there should only be one file here.");
        for (FileItem x : items) {
            log.debug("item: " + x.toString());
        }
    }
    DiskFileItem dfi = (DiskFileItem) items.get(0);
    log.debug("parseRequestForFile - store location: `" + dfi.getStoreLocation() + "'");
    log.debug("dfi content type: " + dfi.getContentType());
    return dfi;
}

From source file:com.netfinworks.rest.convert.MultiPartFormDataParamConvert.java

@SuppressWarnings("rawtypes")
public <T> T convert(Request restRequest, Class<T> paramClass) {
    //multipart/form-data??requestString/inputStream        
    T pojo;//from   www .j a  v  a 2  s .com
    try {
        pojo = paramClass.newInstance();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setFileSizeMax(Magic.MultiPartFileSizeMax);
        List items = upload.parseRequest(restRequest.getRawRequest());
        Iterator iter = items.iterator();//upload.getItemIterator(restRequest.getRawRequest());
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            logger.debug(item.toString());
            if (item.isFormField()) {
                processFormField(item, pojo);
            } else {
                processUploadedFile(item, pojo);
            }
        }
        return pojo;
    } catch (InstantiationException e) {
        logger.error("can't instantiate a pojo of {}, please check the Pojo", paramClass);
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        logger.error("can't invoke none-args constructor of a pojo of {}, please check the Pojo", paramClass);
        throw new RuntimeException(e);
    } catch (FileUploadException e) {
        logger.error("fileupload error.", paramClass);
        throw new RuntimeException(e);
    }
}

From source file:com.skin.generator.action.UploadTestAction.java

/**
 * @param request/*from  w  w w. j av  a 2  s.  co  m*/
 * @return Map<String, Object>
 * @throws Exception
 */
public Map<String, Object> parse(HttpServletRequest request) throws Exception {
    String repository = System.getProperty("java.io.tmpdir");
    int maxFileSize = 1024 * 1024 * 1024;
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setRepository(new File(repository));
    factory.setSizeThreshold(1024 * 1024);
    ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
    servletFileUpload.setFileSizeMax(maxFileSize);
    servletFileUpload.setSizeMax(maxFileSize);
    Map<String, Object> map = new HashMap<String, Object>();
    List<?> list = servletFileUpload.parseRequest(request);

    if (list != null && list.size() > 0) {
        for (Iterator<?> iterator = list.iterator(); iterator.hasNext();) {
            FileItem item = (FileItem) iterator.next();

            if (item.isFormField()) {
                logger.debug("form field: {}, {}", item.getFieldName(), item.toString());
                map.put(item.getFieldName(), item.getString("utf-8"));
            } else {
                logger.debug("file field: {}", item.getFieldName());
                map.put(item.getFieldName(), item);
            }
        }
    }
    return map;
}

From source file:com.skin.taurus.http.servlet.UploadServlet.java

public void upload(HttpRequest request, HttpResponse response) throws IOException {
    int maxFileSize = 1024 * 1024;
    String repository = System.getProperty("java.io.tmpdir");
    DiskFileItemFactory factory = new DiskFileItemFactory();

    factory.setRepository(new File(repository));
    factory.setSizeThreshold(maxFileSize * 2);
    ServletFileUpload servletFileUpload = new ServletFileUpload(factory);

    servletFileUpload.setFileSizeMax(maxFileSize);
    servletFileUpload.setSizeMax(maxFileSize);

    try {//from   w  w w . j  a  v a2  s .co  m
        HttpServletRequest httpRequest = new HttpServletRequestAdapter(request);
        List<?> list = servletFileUpload.parseRequest(httpRequest);

        for (Iterator<?> iterator = list.iterator(); iterator.hasNext();) {
            FileItem item = (FileItem) iterator.next();

            if (item.isFormField()) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Form Field: " + item.getFieldName() + " " + item.toString());
                }
            } else if (!item.isFormField()) {
                if (item.getFieldName() != null) {
                    String fileName = this.getFileName(item.getName());
                    String extension = this.getFileExtensionName(fileName);

                    if (this.isAllowed(extension)) {
                        try {
                            this.save(item);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    item.delete();
                } else {
                    item.delete();
                }
            }
        }
    } catch (FileUploadException e) {
        e.printStackTrace();
    }
}

From source file:AES.Controllers.FileController.java

@RequestMapping(value = "/upload", method = RequestMethod.GET)
public void upload(HttpServletResponse response, HttpServletRequest request,
        @RequestParam Map<String, String> requestParams) throws IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    out.println("Hello<br/>");

    boolean isMultipartContent = ServletFileUpload.isMultipartContent(request);
    if (!isMultipartContent) {
        out.println("You are not trying to upload<br/>");
        return;/*from   w  ww.j  a  va  2  s  .  com*/
    }
    out.println("You are trying to upload<br/>");

    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    try {
        List<FileItem> fields = upload.parseRequest(request);
        out.println("Number of fields: " + fields.size() + "<br/><br/>");
        Iterator<FileItem> it = fields.iterator();
        if (!it.hasNext()) {
            out.println("No fields found");
            return;
        }
        out.println("<table border=\"1\">");
        while (it.hasNext()) {
            out.println("<tr>");
            FileItem fileItem = it.next();
            boolean isFormField = fileItem.isFormField();
            if (isFormField) {
                out.println("<td>regular form field</td><td>FIELD NAME: " + fileItem.getFieldName()
                        + "<br/>STRING: " + fileItem.getString());
                out.println("</td>");
            } else {
                out.println("<td>file form field</td><td>FIELD NAME: " + fileItem.getFieldName()
                        + "<br/>STRING: " + fileItem.getString() + "<br/>NAME: " + fileItem.getName()
                        + "<br/>CONTENT TYPE: " + fileItem.getContentType() + "<br/>SIZE (BYTES): "
                        + fileItem.getSize() + "<br/>TO STRING: " + fileItem.toString());
                out.println("</td>");
                String path = request.getSession().getServletContext().getRealPath("") + "\\uploads\\";
                //System.out.println(request.getSession().getServletContext().getRealPath(""));
                File f = new File(path + fileItem.getName());
                if (!f.exists())
                    f.createNewFile();
                fileItem.write(f);
            }
            out.println("</tr>");
        }
        out.println("</table>");
    } catch (FileUploadException e) {
        e.printStackTrace();
    } catch (Exception ex) {
        Logger.getLogger(FileController.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.darksky.seller.SellerServlet.java

/**
 *   //from   w  ww .j  a  v a 2s. co  m
 * ?
 * @param request
 * @param response
 * @throws Exception
 */
public void modifyShopInfo(HttpServletRequest request, HttpServletResponse response) throws Exception {
    System.out.println();
    System.out.println("--------------------shop modify info-----------------");
    /* ? */
    String sellerID = Seller.getSellerID();

    /* ? */

    String shopID = Shop.getShopID();
    String shopName = null;
    String shopTel = null;
    String shopIntroduction = null;
    String Notice = null;
    String shopAddress = null;
    String shopPhoto = null;

    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();

    ServletFileUpload sfu = new ServletFileUpload(diskFileItemFactory);
    ServletFileUpload sfu2 = new ServletFileUpload(diskFileItemFactory);
    // ?
    sfu.setHeaderEncoding("UTF-8");
    // ?2M
    sfu.setFileSizeMax(1024 * 1024 * 2);
    // ?10M
    sfu.setSizeMax(1024 * 1024 * 10);
    List<FileItem> itemList = sfu.parseRequest(request);

    List<FileItem> itemList2 = sfu2.parseRequest(request);

    FileItem a = null;

    for (FileItem fileItem : itemList) {

        if (!fileItem.isFormField()) {
            a = fileItem;

            System.out.println("QQQQQQQQQQQQQQQQ" + fileItem.toString() + "QQQQQQQQ");

        } else {
            String fieldName = fileItem.getFieldName();
            String value = fileItem.getString("utf-8");
            switch (fieldName) {
            case "shopName":
                shopName = value;
                break;
            case "shopTel":
                shopTel = value;
                break;
            case "shopIntroduction":
                shopIntroduction = value;
                break;
            case "Notice":
                Notice = value;
                break;
            case "shopPhoto":
                shopPhoto = value;
                break;
            case "shopAddress":
                shopAddress = value;
                break;

            default:
                break;
            }

        }

    }
    double randomNum = Math.random();
    shopPhoto = "image/" + shopID + "_" + randomNum + ".jpg";
    String savePath2 = getServletContext().getRealPath("");
    System.out.println("path2=" + savePath2);
    getDish(sellerID);

    String shopSql = null;
    if (a.getSize() != 0) {
        File file2 = new File(savePath2, shopPhoto);
        a.write(file2);

        shopSql = "update shop set shopName='" + shopName + "' , shopTel='" + shopTel + "' , shopIntroduction='"
                + shopIntroduction + "' , Notice='" + Notice + "' , shopAddress='" + shopAddress
                + "',shopPhoto='" + shopPhoto + "' where shopID='" + shopID + "'";
    }

    else {

        shopSql = "update shop set shopName='" + shopName + "' , shopTel='" + shopTel + "' , shopIntroduction='"
                + shopIntroduction + "' , Notice='" + Notice + "' , shopAddress='" + shopAddress
                + "' where shopID='" + shopID + "'";
    }

    System.out.println("shopSql: " + shopSql);

    try {
        statement.executeUpdate(shopSql);
    } catch (SQLException e) {
        e.printStackTrace();
    }

    getShop(Seller.getShopID());
    request.getSession().setAttribute("shop", Shop);

    System.out.println("--------------------shop modify info-----------------");
    System.out.println();

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

From source file:com.darksky.seller.SellerServlet.java

/**
 * * ? /*from ww  w  . ja  v  a2 s.  co m*/
 * @param request
 * @param response
 * @throws Exception
 */
public void addDish(HttpServletRequest request, HttpServletResponse response) throws Exception {
    System.out.println();
    System.out.println("-----------add dish--------------");
    String sellerID = Seller.getSellerID();
    String shopID = Seller.getShopID();
    String dishType = null;
    String dishName = null;
    String dishPrice = null;

    String dishStock = null;
    String dishIntroduction = null;

    if (ServletFileUpload.isMultipartContent(request)) {
        // String savePath = getServletContext().getRealPath("image");

        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();

        ServletFileUpload sfu = new ServletFileUpload(diskFileItemFactory);
        ServletFileUpload sfu2 = new ServletFileUpload(diskFileItemFactory);
        // ?
        sfu.setHeaderEncoding("UTF-8");
        // ?2M
        sfu.setFileSizeMax(1024 * 1024 * 2);
        // ?10M
        sfu.setSizeMax(1024 * 1024 * 10);
        List<FileItem> itemList = sfu.parseRequest(request);

        List<FileItem> itemList2 = sfu2.parseRequest(request);

        FileItem a = null;

        for (FileItem fileItem : itemList) {

            if (!fileItem.isFormField()) {
                a = fileItem;

            } else {
                String fieldName = fileItem.getFieldName();
                String value = fileItem.getString("utf-8");
                switch (fieldName) {
                case "dishName":
                    dishName = value;
                    break;
                case "dishPrice":
                    dishPrice = value;
                    break;

                case "dishIntroduction":
                    dishIntroduction = value;
                    break;
                case "dishStock":
                    dishStock = value;
                    break;
                case "dishType":
                    dishType = value;
                    break;
                default:
                    break;
                }

            }

        }

        String dishPhoto = "image/" + sellerID + "_" + dishName + ".jpg";
        String sql = "insert into dishinfo (dishName,dishType,dishPrice,dishPhoto,shopID,dishIntroduction,dishStock,sellerID) values('"
                + dishName + "','" + dishType + "','" + dishPrice + "','" + dishPhoto + "','" + shopID + "','"
                + dishIntroduction + "','" + dishStock + "','" + sellerID + "')";
        System.out.println(sql);

        String savePath2 = getServletContext().getRealPath("");
        System.out.println("path2=" + savePath2);

        File file1 = new File(savePath2, dishPhoto);
        System.out.println(
                ""
                        + a.toString());
        a.write(file1);
        System.out.println("?");

        try {
            statement.execute(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    getDish(sellerID);
    request.getSession().setAttribute("dish", DishList);
    request.getRequestDispatcher("?.jsp").forward(request, response);
    System.out.println("-----------add dish--------------");
    System.out.println();

}

From source file:org.codelabor.system.file.web.controller.xplatform.FileController.java

@RequestMapping("/upload-test")
public String upload(Model model, HttpServletRequest request, ServletContext context) throws Exception {
    logger.debug("upload-teset");
    DataSetList outputDataSetList = new DataSetList();
    VariableList outputVariableList = new VariableList();

    try {/*from w ww .  j  av a2 s  . c  o m*/

        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        Map<String, Object> paramMap = RequestUtils.getParameterMap(request);
        logger.debug("paramMap: {}", paramMap.toString());

        String mapId = (String) paramMap.get("mapId");
        RepositoryType acceptedRepositoryType = repositoryType;
        String requestedRepositoryType = (String) paramMap.get("repositoryType");
        if (StringUtils.isNotEmpty(requestedRepositoryType)) {
            acceptedRepositoryType = RepositoryType.valueOf(requestedRepositoryType);
        }

        if (isMultipart) {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(sizeThreshold);
            factory.setRepository(new File(tempRepositoryPath));
            factory.setFileCleaningTracker(FileCleanerCleanup.getFileCleaningTracker(context));

            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setFileSizeMax(fileSizeMax);
            upload.setSizeMax(requestSizeMax);
            upload.setHeaderEncoding(characterEncoding);
            upload.setProgressListener(new FileUploadProgressListener());

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

            while (iter.hasNext()) {
                FileItem fileItem = iter.next();
                logger.debug("fileItem: {}", fileItem.toString());
                FileDTO fileDTO = null;
                if (fileItem.isFormField()) {
                    paramMap.put(fileItem.getFieldName(), fileItem.getString(characterEncoding));
                } else {
                    if (fileItem.getName() == null || fileItem.getName().length() == 0)
                        continue;
                    // set DTO
                    fileDTO = new FileDTO();
                    fileDTO.setMapId(mapId);
                    fileDTO.setRealFilename(FilenameUtils.getName(fileItem.getName()));
                    if (acceptedRepositoryType == RepositoryType.FILE_SYSTEM) {
                        fileDTO.setUniqueFilename(uniqueFilenameGenerationService.getNextStringId());
                    }
                    fileDTO.setContentType(fileItem.getContentType());
                    fileDTO.setRepositoryPath(realRepositoryPath);
                    logger.debug("fileDTO: {}", fileDTO.toString());
                    UploadUtils.processFile(acceptedRepositoryType, fileItem.getInputStream(), fileDTO);
                }
                if (fileDTO != null)
                    fileManager.insertFile(fileDTO);
            }
        } else {
        }
        XplatformUtils.setSuccessMessage(
                messageSource.getMessage("info.success", new Object[] {}, forcedLocale), outputVariableList);
        logger.debug("success");
    } catch (Exception e) {
        logger.error("fail");
        e.printStackTrace();
        logger.error(e.getMessage());
        throw new XplatformException(messageSource.getMessage("error.failure", new Object[] {}, forcedLocale),
                e);
    }
    model.addAttribute(OUTPUT_DATA_SET_LIST, outputDataSetList);
    model.addAttribute(OUTPUT_VARIABLE_LIST, outputVariableList);
    return VIEW_NAME;

}

From source file:org.codelabor.system.file.web.servlet.FileUploadServlet.java

/**
 * ??  .</br> ? ? ?? ?  , (: ?) ? mapId  . ?
 *  ?? ? repositoryType ,  ?//from w  ww  .  ja  va 2 s.c o m
 * org.codelabor.system.file.RepositoryType .
 * 
 * @param request
 *            
 * @param response
 *            ?
 * @throws Exception
 *             
 */
@SuppressWarnings("unchecked")
protected void upload(HttpServletRequest request, HttpServletResponse response) throws Exception {
    WebApplicationContext ctx = WebApplicationContextUtils
            .getRequiredWebApplicationContext(this.getServletContext());
    FileManager fileManager = (FileManager) ctx.getBean("fileManager");

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    Map<String, Object> paramMap = RequestUtils.getParameterMap(request);
    logger.debug("paramMap: {}", paramMap.toString());

    String mapId = (String) paramMap.get("mapId");
    RepositoryType acceptedRepositoryType = repositoryType;
    String requestedRepositoryType = (String) paramMap.get("repositoryType");
    if (StringUtils.isNotEmpty(requestedRepositoryType)) {
        acceptedRepositoryType = RepositoryType.valueOf(requestedRepositoryType);
    }

    if (isMultipart) {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(sizeThreshold);
        factory.setRepository(new File(tempRepositoryPath));
        factory.setFileCleaningTracker(FileCleanerCleanup.getFileCleaningTracker(this.getServletContext()));

        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setFileSizeMax(fileSizeMax);
        upload.setSizeMax(requestSizeMax);
        upload.setHeaderEncoding(characterEncoding);
        upload.setProgressListener(new FileUploadProgressListener());
        try {
            List<FileItem> fileItemList = upload.parseRequest(request);
            Iterator<FileItem> iter = fileItemList.iterator();

            while (iter.hasNext()) {
                FileItem fileItem = iter.next();
                logger.debug("fileItem: {}", fileItem.toString());
                FileDTO fileDTO = null;
                if (fileItem.isFormField()) {
                    paramMap.put(fileItem.getFieldName(), fileItem.getString(characterEncoding));
                } else {
                    if (fileItem.getName() == null || fileItem.getName().length() == 0)
                        continue;
                    // set DTO
                    fileDTO = new FileDTO();
                    fileDTO.setMapId(mapId);
                    fileDTO.setRealFilename(FilenameUtils.getName(fileItem.getName()));
                    if (acceptedRepositoryType == RepositoryType.FILE_SYSTEM) {
                        fileDTO.setUniqueFilename(getUniqueFilename());
                    }
                    fileDTO.setContentType(fileItem.getContentType());
                    fileDTO.setRepositoryPath(realRepositoryPath);
                    logger.debug("fileDTO: {}", fileDTO.toString());
                    UploadUtils.processFile(acceptedRepositoryType, fileItem.getInputStream(), fileDTO);
                }
                if (fileDTO != null)
                    fileManager.insertFile(fileDTO);
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            throw e;
        }
    } else {
        paramMap = RequestUtils.getParameterMap(request);
    }
    try {
        processParameters(paramMap);
    } catch (Exception e) {
        e.printStackTrace();
        logger.error(e.getMessage());
        throw e;
    }
    dispatch(request, response, forwardPathUpload);
}

From source file:org.deegree.services.controller.OGCFrontController.java

/**
 * Checks if the given request is a multi part request. If so it will return the multiparts as a list of
 * {@link FileItem} else <code>null</code> will be returned.
 * /*from ww  w . j av a  2s . c o  m*/
 * @param request
 *            to check
 * @return a list of multiparts or <code>null</code> if it was not a multipart request.
 * @throws FileUploadException
 *             if there are problems reading/parsing the request or storing files.
 */
private List<FileItem> checkAndRetrieveMultiparts(HttpServletRequest request) throws FileUploadException {
    List<FileItem> result = null;
    if (ServletFileUpload.isMultipartContent(request)) {
        // Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();
        LOG.debug("The incoming request is a multipart request.");
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Parse the request
        result = upload.parseRequest(request);
        LOG.debug("The multipart request contains: " + result.size() + " items.");
        OwsGlobalConfigLoader loader = workspace.getNewWorkspace()
                .getInitializable(OwsGlobalConfigLoader.class);
        if (loader.getRequestLogger() != null) { // TODO, this is not actually something of the
            // request logger, what is
            // actually logged here?
            for (FileItem item : result) {
                LOG.debug(item.toString());
            }
        }
    }
    return result;
}