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

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

Introduction

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

Prototype

boolean isFormField();

Source Link

Document

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

Usage

From source file:edu.temple.cis3238.wiki.ui.servlets.UploaderServlet.java

/**
 * Processes requests for HTTP  <code>POST</code> method.
 *
 * @param request  servlet request/*from  w ww.j  av a 2s  .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:cn.vlabs.duckling.vwb.ui.servlet.SimpleUploaderServlet.java

private Map<String, Object> parseFileItem(HttpServletRequest request)
        throws FileUploadException, UnsupportedEncodingException {
    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(fileItemFactory);
    upload.setHeaderEncoding("UTF-8");
    List<?> items = upload.parseRequest(request);

    Map<String, Object> fields = new HashMap<String, Object>();

    Iterator<?> iter = items.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();
        if (item.isFormField()) {
            fields.put(item.getFieldName(), item.getString("UTF-8"));
        } else {/*w w  w.  j ava  2 s. c  o  m*/
            fields.put(item.getFieldName(), item);
        }
    }
    return fields;
}

From source file:com.javaweb.controller.SuaTinTucServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request servlet request/*w  ww  .  ja  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, ParseException {
    response.setContentType("text/html;charset=UTF-8");
    request.setCharacterEncoding("UTF-8");

    //response.setCharacterEncoding("UTF-8");
    HttpSession session = request.getSession();
    String TieuDe = "", NoiDung = "", ngaydang = "", GhiChu = "", fileName = "";
    int idloaitin = 0, idTK = 0, idtt = 0;

    TintucService tintucservice = new TintucService();

    //File upload
    String folderupload = getServletContext().getInitParameter("file-upload");
    String rootPath = getServletContext().getRealPath("/");
    filePath = rootPath + folderupload;
    isMultipart = ServletFileUpload.isMultipartContent(request);
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();

    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:\\Windows\\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();

        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            if (!fi.isFormField()) {
                // Get the uploaded file parameters

                String fieldName = fi.getFieldName();
                fileName = fi.getName();
                String contentType = fi.getContentType();
                boolean isInMemory = fi.isInMemory();
                long sizeInBytes = fi.getSize();

                //change file name
                fileName = FileService.ChangeFileName(fileName);

                // 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>");
            }

            if (fi.isFormField()) {
                if (fi.getFieldName().equalsIgnoreCase("TieuDe")) {
                    TieuDe = fi.getString("UTF-8");
                } else if (fi.getFieldName().equalsIgnoreCase("NoiDung")) {
                    NoiDung = fi.getString("UTF-8");
                } else if (fi.getFieldName().equalsIgnoreCase("NgayDang")) {
                    ngaydang = fi.getString("UTF-8");
                } else if (fi.getFieldName().equalsIgnoreCase("GhiChu")) {
                    GhiChu = fi.getString("UTF-8");
                } else if (fi.getFieldName().equalsIgnoreCase("loaitin")) {
                    idloaitin = Integer.parseInt(fi.getString("UTF-8"));
                } else if (fi.getFieldName().equalsIgnoreCase("idtaikhoan")) {
                    idTK = Integer.parseInt(fi.getString("UTF-8"));
                } else if (fi.getFieldName().equalsIgnoreCase("idtt")) {
                    idtt = Integer.parseInt(fi.getString("UTF-8"));
                }
            }
        }

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

    Date NgayDang = new SimpleDateFormat("yyyy-MM-dd").parse(ngaydang);

    Tintuc tt = tintucservice.GetTintucID(idtt);

    tt.setIdTaiKhoan(idTK);
    tt.setTieuDe(TieuDe);
    tt.setNoiDung(NoiDung);
    tt.setNgayDang(NgayDang);
    tt.setGhiChu(GhiChu);
    if (!fileName.equals("")) {
        if (tt.getImgLink() != null) {
            if (!tt.getImgLink().equals(fileName)) {
                tt.setImgLink(fileName);
            }
        } else {
            tt.setImgLink(fileName);
        }
    }

    boolean rs = tintucservice.InsertTintuc(tt);
    if (rs) {
        session.setAttribute("kiemtra", "1");
        response.sendRedirect("SuaTinTuc.jsp?idTintuc=" + idtt);
    } else {
        session.setAttribute("kiemtra", "0");
        response.sendRedirect("SuaTinTuc.jsp?idTintuc=" + idtt);
    }

    //        try (PrintWriter out = response.getWriter()) {
    //            /* TODO output your page here. You may use following sample code. */
    //            out.println("<!DOCTYPE html>");
    //            out.println("<html>");
    //            out.println("<head>");
    //            out.println("<title>Servlet SuaTinTucServlet</title>");            
    //            out.println("</head>");
    //            out.println("<body>");
    //            out.println("<h1>Servlet SuaTinTucServlet at " + request.getContextPath() + "</h1>");
    //            out.println("</body>");
    //            out.println("</html>");
    //        }
}

From source file:com.larasolution.serverlts.FileUploadHandler.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //     tablename=request.getParameter(tablename)
    //process only if its multipart content
    FileOutputStream fos = new FileOutputStream("C:\\uploads\\data.csv");
    String list = "";
    List<List> allData = new ArrayList<List>();

    List<String> parameters = new ArrayList<String>();
    if (ServletFileUpload.isMultipartContent(request)) {

        try {//from ww  w .  j av a  2 s  .  c  o  m

            StringBuilder data = new StringBuilder();
            List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
            System.out.println(multiparts);
            for (FileItem item : multiparts) {
                if (item.isFormField()) {
                    parameters.add(item.getFieldName());
                    System.out.println(parameters);
                }
                if (!item.isFormField()) {
                    String name = new File(item.getName()).getName();

                    item.write(new File(UPLOAD_DIRECTORY + File.separator + name));
                    //System.out.println(File.separator);
                    // Get the workbook object for XLSX file
                    XSSFWorkbook wBook = new XSSFWorkbook(
                            new FileInputStream(UPLOAD_DIRECTORY + File.separator + name));

                    XSSFSheet zz = wBook.getSheetAt(0);
                    FormulaEvaluator formulaEval = wBook.getCreationHelper().createFormulaEvaluator();

                    Row row;
                    Cell cell;

                    // Iterate through each rows from first sheet
                    Iterator<Row> rowIterator = zz.iterator();
                    while (rowIterator.hasNext()) {
                        row = rowIterator.next();

                        // For each row, iterate through each columns
                        Iterator<Cell> cellIterator = row.cellIterator();

                        while (cellIterator.hasNext()) {

                            cell = cellIterator.next();

                            switch (cell.getCellType()) {
                            case Cell.CELL_TYPE_BOOLEAN:
                                data.append(cell.getBooleanCellValue()).append(",");
                                break;
                            case Cell.CELL_TYPE_NUMERIC:
                                if (DateUtil.isCellDateFormatted(cell)) {
                                    data.append(
                                            com.larasolution.modle.getDate.getDate5(cell.getDateCellValue()))
                                            .append(",");
                                } else {
                                    data.append(cell.getNumericCellValue()).append(",");
                                }

                                break;
                            case Cell.CELL_TYPE_STRING:
                                data.append(cell.getStringCellValue()).append(",");
                                break;
                            case Cell.CELL_TYPE_BLANK:
                                data.append("" + ",");
                                break;
                            case Cell.CELL_TYPE_FORMULA:
                                Double value = Double.parseDouble(formulaEval.evaluate(cell).formatAsString());

                                data.append(String.format("%.2f", value)).append(",");
                                break;
                            default:
                                data.append(cell).append("");

                            }

                        }
                        data.append("\r\n");
                        //String k = data.substring(0, data.length() - 3);
                        //ls.add(k);

                        // data.setLength(0);
                    }

                    fos.write(data.toString().getBytes());
                    fos.close();

                    //
                }
            }

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

    } else {
        request.setAttribute("message", "Sorry this Servlet only handles file upload request");
    }

    request.setAttribute("arrayfile", allData);
    request.setAttribute("names", parameters);
    RequestDispatcher disp = getServletContext().getRequestDispatcher("/FileUploadResult.jsp");
    disp.forward(request, response);

    // System.out.println(allData.size());
    // response.sendRedirect("send.jsp?arrayfile=" + list + "");
    //request.getRequestDispatcher("/send.jsp?arrayfile='"+ls+"'").forward(request, response);
}

From source file:com.liferay.server.manager.internal.executor.PluginExecutor.java

protected FileItem getFileItem(HttpServletRequest request) throws FileUploadException {

    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();

    ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);

    List<FileItem> fileItems = servletFileUpload.parseRequest(request);

    for (FileItem fileItem : fileItems) {
        if (!fileItem.isFormField()) {
            return fileItem;
        }//  w ww .ja v a  2  s  .c  o m
    }

    return null;
}

From source file:ex.fileupload.spring.GFileUploadSupport.java

/**
 * Parse the given List of Commons FileItems into a Spring
 * MultipartParsingResult, containing Spring MultipartFile instances and a
 * Map of multipart parameter./*from w ww  .j a  v  a 2  s  . com*/
 * 
 * @param fileItems
 *            the Commons FileIterms to parse
 * @param encoding
 *            the encoding to use for form fields
 * @return the Spring MultipartParsingResult
 * @see GMultipartFile#CommonsMultipartFile(org.apache.commons.fileupload.FileItem)
 */
protected MultipartParsingResult parseFileItems(List<FileItem> fileItems, String encoding) {
    MultiValueMap<String, MultipartFile> multipartFiles = new LinkedMultiValueMap<String, MultipartFile>();
    Map<String, String[]> multipartParameters = new HashMap<String, String[]>();
    Map<String, String> multipartParameterContentTypes = new HashMap<String, String>();

    // Extract multipart files and multipart parameters.
    for (FileItem fileItem : fileItems) {
        if (fileItem.isFormField()) {
            String value = null;
            if (encoding != null) {
                try {
                    value = fileItem.getString(encoding);
                } catch (UnsupportedEncodingException ex) {
                    if (logger.isWarnEnabled()) {
                        logger.warn("Could not decode multipart item '" + fileItem.getFieldName()
                                + "' with encoding '" + encoding + "': using platform default");
                    }
                    value = fileItem.getString();
                }
            } else {
                value = fileItem.getString();
            }
            String[] curParam = multipartParameters.get(fileItem.getFieldName());
            if (curParam == null) {
                // simple form field
                multipartParameters.put(fileItem.getFieldName(), new String[] { value });
            } else {
                // array of simple form fields
                String[] newParam = StringUtils.addStringToArray(curParam, value);
                multipartParameters.put(fileItem.getFieldName(), newParam);
            }
            multipartParameterContentTypes.put(fileItem.getName(), fileItem.getContentType());
        } else {
            // multipart file field
            GMultipartFile file = new GMultipartFile(fileItem);
            multipartFiles.add(file.getName(), file);
            if (logger.isDebugEnabled()) {
                logger.debug("Found multipart file [" + file.getName() + "] of size " + file.getSize()
                        + " bytes with original filename [" + file.getOriginalFilename() + "], stored "
                        + file.getStorageDescription());
            }
        }
    }
    return new MultipartParsingResult(multipartFiles, multipartParameters, multipartParameterContentTypes);
}

From source file:calliope.handler.put.AesePutHandler.java

private void parseRequest(HttpServletRequest request) throws AeseException {
    try {/* ww  w  . ja v  a  2 s  . co m*/
        FileItemFactory factory = new DiskFileItemFactory();
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        // 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) {
                    String contents = item.getString();
                    if (fieldName.equals(Params.STRIPPER))
                        stripperName = contents;
                    else if (fieldName.equals(Params.ENCODING))
                        encoding = contents;
                    else if (fieldName.equals(Params.STYLE))
                        style = contents;
                    else if (fieldName.equals(Params.TITLE))
                        title = contents;
                    else if (fieldName.equals(Params.VERSION1))
                        version1 = contents;
                    else if (fieldName.equals(Params.AUTHOR))
                        author = contents;
                    else if (fieldName.equals(Params.DESCRIPTION))
                        description = contents;
                }
            } else if (item.getName().length() > 0) {
                byte[] rawData = item.get();
                guessEncoding(rawData);
                if (encoding == null)
                    encoding = guessEncoding(rawData);
                fileContent = new String(rawData, encoding);
            }
        }
    } catch (Exception e) {
        throw new AeseException(e);
    }
}

From source file:ReceiveImage.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*w  w  w.  j a  va 2s. co  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    System.out.println(isMultipart = ServletFileUpload.isMultipartContent(request));

    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();
        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            System.out.println(fi.isFormField());
            if (fi.isFormField()) {
                System.out.println("Got a form field: " + fi.getFieldName() + " " + fi);
            } else {
                // Get the uploaded file parameters
                //System.out.println(fi.getString("Command"));

                String fieldName = fi.getFieldName();
                String fileName = fi.getName();
                String contentType = fi.getContentType();
                boolean isInMemory = fi.isInMemory();

                System.out.println(fieldName);
                System.out.println(fileName);
                String courseHour, course, regNo, date, temp = fileName;
                int j = temp.indexOf("sep");

                courseHour = temp.substring(0, j);
                temp = temp.substring(j + 3);

                j = temp.indexOf("sep");

                course = temp.substring(0, j);

                temp = temp.substring(j + 3);

                j = temp.indexOf("sep");

                regNo = temp.substring(0, j);

                date = temp.substring(j + 3);
                date = date.replaceAll("s", "-");

                System.out.println("ualal" + courseHour + course + regNo + date);

                System.out.println(contentType);

                long sizeInBytes = fi.getSize();
                // Write the file

                String uploadFolder = getServletContext().getRealPath("") + "Photo\\" + course + "\\" + regNo
                        + "\\";
                //                    String uploadFolder =  "\\SUST_PHOTO_PRESENT\\Photo\\" + course + "\\" + regNo + "\\";

                uploadFolder = uploadFolder.replace("\\build", "");
                Path path = Paths.get(uploadFolder);
                //if directory exists?
                if (!Files.exists(path)) {
                    try {
                        Files.createDirectories(path);
                    } catch (IOException e) {
                        //fail to create directory
                        e.printStackTrace();
                    }
                }
                //uploadFolder+= "\\"+date+".jpg";   
                System.out.println(fileName);
                System.out.println(uploadFolder);

                //               
                file = new File(uploadFolder + date);

                date = date.replaceAll("-", "/");
                date = date.substring(0, 10);

                String total_url = uploadFolder + date.replaceAll("/", "-") + ".jpg";
                System.out.println(total_url);

                String formattedUrl = total_url.replaceAll("\\\\", "/");

                System.out.println(formattedUrl.substring(38));

                System.out.println("-------------->>>>>>>>" + course + "  " + date + regNo + total_url);

                AddUser.updateUrl(courseHour, course, date, regNo, formattedUrl.substring(38));
                fi.write(file);

                //                    System.out.println("-------------->>>>>>>>" +course+"  "+ date+ regNo+total_url);
                //                   try {
                //            SavePhoto.saveIMG("CSE", "2016", "tada","F:\\1.png");
                //        } catch (IOException ex) {
                //            Logger.getLogger(SavePhoto.class.getName()).log(Level.SEVERE, null, ex);
                //        }
                System.out.println(uploadFolder);
            }
        }
    } catch (Exception ex) {
        System.out.println(ex);
    }
}

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

/**
 * ?/*from w w  w.  jav a  2s .com*/
 */
private void processFileUpload(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String serviceKey = request.getParameter("serviceKey");
    if (serviceKey == null) {
        serviceKey = "global";
    }

    int maxUploadSize = conf.getInt(serviceKey + ".maxUploadSize", 0);
    if (maxUploadSize == 0) {
        maxUploadSize = conf.getInt("upload.maxUploadSize", 10);// 10MB
    }
    maxUploadSize = maxUploadSize * FileUtils.MB_SIZE;
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // ?
    factory.setSizeThreshold(204800);
    File tempDir = new File(getUploadDir() + "/temp");
    if (!tempDir.exists()) {
        tempDir.mkdir();
    }

    // ?
    factory.setRepository(tempDir);
    ServletFileUpload upload = new ServletFileUpload(factory);
    // ?
    upload.setFileSizeMax(maxUploadSize);
    // request
    upload.setSizeMax(maxUploadSize);
    upload.setProgressListener(new FileUploadListener(request));
    upload.setHeaderEncoding("UTF-8");
    // ???FileUploadStatus Bean
    FileMgmtFactory.saveStatusBean(request, initStatusBean(request));

    try {
        List<?> items = upload.parseRequest(request);
        // url
        for (int i = 0; i < items.size(); i++) {
            FileItem item = (FileItem) items.get(i);
            if (item.isFormField()) {

                break;
            }
        }
        // 
        String uploadDir = com.glaf.base.utils.StringUtil.createDir(getUploadDir());
        // ?
        for (int i = 0; i < items.size(); i++) {
            FileItem item = (FileItem) items.get(i);
            // ?
            if (FileMgmtFactory.getStatusBean(request).getCancel()) {
                deleteUploadedFile(request);
                break;
            } else if (!item.isFormField() && item.getName().length() > 0) {
                logger.debug("" + item.getName());
                // ?
                String fileId = UUID32.getUUID();
                String path = uploadDir + FileUtils.sp + fileId;
                File uploadedFile = new File(new File(getUploadDir(), uploadDir), fileId);
                item.write(uploadedFile);
                // 
                FileUploadStatus satusBean = FileMgmtFactory.getStatusBean(request);
                FileInfo fileInfo = new FileInfo();
                fileInfo.setCreateDate(new Date());
                fileInfo.setFileId(fileId);
                fileInfo.setFile(uploadedFile);
                fileInfo.setFilename(FileUtils.getFilename(item.getName()));
                fileInfo.setSize(item.getSize());
                fileInfo.setPath(path);
                satusBean.getUploadFileUrlList().add(fileInfo);
                FileMgmtFactory.saveStatusBean(request, satusBean);
                Thread.sleep(500);
            }
        }

    } catch (FileUploadException ex) {
        uploadExceptionHandle(request, "?:" + ex.getMessage());
    } catch (Exception ex) {
        uploadExceptionHandle(request, "??:" + ex.getMessage());
    }
    String forwardURL = request.getParameter("forwardURL");
    if (StringUtils.isEmpty(forwardURL)) {
        forwardURL = "/others/attachment.do?method=showResult";
    }
    request.getRequestDispatcher(forwardURL).forward(request, response);
}

From source file:cn.trymore.core.web.servlet.FileUploadServlet.java

@Override
@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");

    try {/* w w  w  .  j a va  2s  . c o  m*/
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
        diskFileItemFactory.setSizeThreshold(4096);
        diskFileItemFactory.setRepository(new File(this.tempPath));

        String fileIds = "";

        ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
        List<FileItem> fileList = (List<FileItem>) servletFileUpload.parseRequest(request);
        Iterator<FileItem> itor = fileList.iterator();
        Iterator<FileItem> itor1 = fileList.iterator();
        String file_type = "";
        while (itor1.hasNext()) {
            FileItem item = itor1.next();
            if (item.isFormField() && "file_type".equals(item.getFieldName())) {
                file_type = item.getString();
            }
        }
        FileItem fileItem;
        while (itor.hasNext()) {
            fileItem = itor.next();

            if (fileItem.getContentType() == null) {
                continue;
            }

            // obtains the file path and name
            String filePath = fileItem.getName();

            String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
            // generates new file name with the current time stamp.
            String newFileName = this.fileCat + "/" + UtilFile.generateFilename(fileName);
            // ensure the directory existed before creating the file.
            File dir = new File(
                    this.uploadPath + "/" + newFileName.substring(0, newFileName.lastIndexOf("/") + 1));
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // stream writes to the destination file
            fileItem.write(new File(this.uploadPath + "/" + newFileName));

            ModelFileAttach fileAttach = null;
            if (request.getParameter("noattach") == null) {
                // storages the file into database.
                fileAttach = new ModelFileAttach();
                fileAttach.setFileName(fileName);
                fileAttach.setFilePath(newFileName);
                fileAttach.setTotalBytes(Long.valueOf(fileItem.getSize()));
                fileAttach.setNote(this.getStrFileSize(fileItem.getSize()));
                fileAttach.setFileExt(fileName.substring(fileName.lastIndexOf(".") + 1));
                fileAttach.setCreatetime(new Date());
                fileAttach.setDelFlag(ModelFileAttach.FLAG_NOT_DEL);
                fileAttach.setFileType(!"".equals(file_type) ? file_type : this.fileCat);

                ModelAppUser user = ContextUtil.getCurrentUser();
                if (user != null) {
                    fileAttach.setCreatorId(Long.valueOf(user.getId()));
                    fileAttach.setCreator(user.getFullName());
                } else {
                    fileAttach.setCreator("Unknow");
                }

                this.serviceFileAttach.save(fileAttach);
            }

            //add by Tang ??fileIds?????
            if (fileAttach != null) {
                fileIds = (String) request.getSession().getAttribute("fileIds");
                if (fileIds == null) {
                    fileIds = fileAttach.getId();
                } else {
                    fileIds = fileIds + "," + fileAttach.getId();
                }
            }
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter writer = response.getWriter();
            writer.println(
                    "{\"status\": 1, \"data\":{\"id\":" + (fileAttach != null ? fileAttach.getId() : "\"\"")
                            + ", \"url\":\"" + newFileName + "\"}}");
        }
        request.getSession().setAttribute("fileIds", fileIds);
    } catch (Exception e) {
        e.printStackTrace();
        response.getWriter().write("{\"status\":0, \"message\":\":" + e.getMessage() + "\"");
    }
}