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

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

Introduction

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

Prototype

String getName();

Source Link

Document

Returns the original filename in the client's filesystem, as provided by the browser (or other client software).

Usage

From source file:jp.co.opentone.bsol.linkbinder.view.filter.UploadFileFilter.java

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {

    // ????/*from  w ww.j a  v a 2 s  . co m*/
    if (!(req instanceof HttpServletRequest)) {
        chain.doFilter(req, res);
        return;
    }

    HttpServletRequest httpReq = (HttpServletRequest) req;
    // ??????????
    if (!ServletFileUpload.isMultipartContent(httpReq)) {
        chain.doFilter(req, res);
        return;
    }

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

    factory.setSizeThreshold(thresholdSize);
    sfu.setSizeMax(maxSize); //
    sfu.setHeaderEncoding(req.getCharacterEncoding());

    try {
        @SuppressWarnings("unchecked")
        Iterator<FileItem> ite = sfu.parseRequest(httpReq).iterator();
        List<String> keys = new ArrayList<String>();
        List<String> names = new ArrayList<String>();
        List<String> fieldNames = new ArrayList<String>();
        List<Long> fileSize = new ArrayList<Long>();

        while (ite.hasNext()) {
            String name = null;
            FileItem item = ite.next();

            // ????
            if (!(item.isFormField())) {
                name = item.getName();
                name = name.substring(name.lastIndexOf('\\') + 1);
                if (StringUtils.isEmpty(name)) {
                    continue;
                }
                File f = null;
                // CHECKSTYLE:OFF
                // ??????????.
                while ((f = new File(createTempFilePath())).exists()) {
                }
                // CHECKSTYLE:ON
                if (!validateByteLength(name, maxFilenameLength, minFilenameLength)) {
                    // ????
                    names.add(name);
                    keys.add(UploadedFile.KEY_FILENAME_OVER);
                    fieldNames.add(item.getFieldName());
                    fileSize.add(item.getSize());
                } else if (item.getSize() == 0) {
                    // 0
                    names.add(name);
                    keys.add(UploadedFile.KEY_SIZE_ZERO);
                    fieldNames.add(item.getFieldName());
                    fileSize.add(item.getSize());
                } else if (maxFileSize > 0 && item.getSize() > maxFileSize) {
                    // ?
                    // ?0??????Validation
                    names.add(name);
                    keys.add(UploadedFile.KEY_SIZE_OVER);
                    fieldNames.add(item.getFieldName());
                    fileSize.add(item.getSize());
                } else {
                    item.write(f);
                    names.add(name);
                    keys.add(f.getName());
                    fieldNames.add(item.getFieldName());
                    fileSize.add(item.getSize());
                }
                f.deleteOnExit();
            }
        }

        // 
        UploadFileFilterResult result = new UploadFileFilterResult();
        result.setResult(UploadFileFilterResult.RESULT_OK);
        result.setNames(names.toArray(new String[names.size()]));
        result.setKeys(keys.toArray(new String[keys.size()]));
        result.setFieldNames(fieldNames.toArray(new String[fieldNames.size()]));
        result.setFileSize(fileSize.toArray(new Long[fileSize.size()]));
        writeResponse(req, res, result);
    } catch (Exception e) {
        e.printStackTrace();
        // 
        UploadFileFilterResult result = new UploadFileFilterResult();
        result.setResult(UploadFileFilterResult.RESULT_NG);
        writeResponse(req, res, result);
    }
}

From source file:com.example.app.support.ui.vtcrop.VTCropPictureEditor.java

/**
 * Create an instance./*w  ww  .  j  a va  2 s  .  c  o m*/
 *
 * @param cfg the configuration
 */
public VTCropPictureEditor(VTCropPictureEditorConfig cfg) {
    super();
    addClassName("picture-editor");
    _config = cfg;

    _picture.setImageCaching(false);
    _fileField.addClassName("custom-file");
    _fileField.setAccept("image/*");
    _fileField.addPropertyChangeListener(FileField.PROP_FILE_ITEMS, evt -> {
        @SuppressWarnings("unchecked")
        final List<FileItem> files = (List<FileItem>) evt.getNewValue();
        if (files != null && files.size() > 0) {
            _uiValue = files.get(0);
            if (files.size() > 1) {
                _additionalUiValues.clear();
                for (int i = 1; i < files.size(); i++) {
                    FileItem file = files.get(i);
                    _additionalUiValues.put(file.getName(), file);
                }
            }
            _picture.setImage(new Image(_uiValue));
            _modified = true;
        }
        _fileField.resetFile();
    });
}

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

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request servlet request/*  w  w w .  j a va2 s.co 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();
    //        session.removeAttribute("errorreg");
    String TieuDe = "", NoiDung = "", ngaydang = "", GhiChu = "", fileName = "";
    int idloaitin = 0, idTK = 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"));
                }
            }
        }

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

    Date NgayDang = new SimpleDateFormat("yyyy-MM-dd").parse(ngaydang);
    Tintuc tintuc = new Tintuc(idloaitin, idTK, fileName, TieuDe, NoiDung, NgayDang, GhiChu);

    boolean rs = tintucservice.InsertTintuc(tintuc);
    if (rs) {
        session.setAttribute("kiemtra", "1");
        String url = "ThemTinTuc.jsp";
        response.sendRedirect(url);
    } else {
        session.setAttribute("kiemtra", "0");
        String url = "ThemTinTuc.jsp";
        response.sendRedirect(url);
    }

    //        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 ThemTinTucServlet</title>");            
    //            out.println("</head>");
    //            out.println("<body>");
    //            out.println("<h1>Servlet ThemTinTucServlet at " + request.getContextPath() + "</h1>");
    //            out.println("</body>");
    //            out.println("</html>");
    //        }
}

From source file:Controller.ControllerCustomers.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*w  ww .  ja  va  2  s  . c om*/
 * @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);
    if (!isMultipart) {

    } else {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List items = null;
        try {
            items = upload.parseRequest(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Iterator iter = items.iterator();
        Hashtable params = new Hashtable();
        String fileName = null;
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (item.isFormField()) {
                params.put(item.getFieldName(), item.getString());
            } else {

                try {
                    String itemName = item.getName();
                    fileName = itemName.substring(itemName.lastIndexOf("\\") + 1);
                    String RealPath = getServletContext().getRealPath("/") + "upload\\" + fileName;
                    String username = (String) params.get("txtusername");
                    String password = (String) params.get("txtpassword");
                    String hoten = (String) params.get("txthoten");
                    String gioitinh = (String) params.get("txtgioitinh");
                    String email = (String) params.get("txtemail");
                    String role = (String) params.get("txtrole");
                    String anh = (String) params.get("txtanh");
                    //Update  product
                    if (fileName.equals("")) {

                        Customer Cus = new Customer(username, password, hoten, gioitinh, email, role, anh);
                        CustomerDAO.SuaThongTinKhachHang(Cus);
                        RequestDispatcher rd = request.getRequestDispatcher("CustomerDao.jsp");
                        rd.forward(request, response);

                    } else {
                        // bat dau ghi file
                        File savedFile = new File(RealPath);
                        item.write(savedFile);
                        //ket thuc ghi

                        Customer Cus = new Customer(username, password, hoten, gioitinh, email, role,
                                "upload\\" + fileName);
                        CustomerDAO.SuaThongTinKhachHang(Cus);

                        RequestDispatcher rd = request.getRequestDispatcher("CustomerDao.jsp");
                        rd.forward(request, response);
                    }

                } catch (Exception e) {
                    System.out.println(e);
                    RequestDispatcher rd = request.getRequestDispatcher("InformationError.jsp");
                    rd.forward(request, response);
                }
            }

        }
    }

}

From source file:com.krawler.spring.hrms.common.hrmsExtApplDocsDAOImpl.java

public KwlReturnObject uploadFile(FileItem fi, String userid, HashMap arrparam, String uploadedby)
        throws ServiceException {
    HrmsDocs docObj = new HrmsDocs();
    List ll = new ArrayList();
    int dl = 0;/* ww w .  j  ava 2 s  . c o  m*/
    try {
        String fileName = new String(fi.getName().getBytes(), "UTF8");
        String Ext = "";
        String a = "";

        if (fileName.contains(".")) {
            Ext = fileName.substring(fileName.indexOf(".") + 1, fileName.length());
            a = Ext.toUpperCase();
        }
        if (arrparam.get("IsIE").equals("true")) {
            int cnt = fileName.indexOf("\\");
            while (cnt != -1) {
                fileName = fileName.substring(cnt + 1, fileName.length());
                cnt = fileName.indexOf("\\");
            }
        }
        //            Jobapplicant jobapp = (Jobapplicant) hibernateTemplate.get(Jobapplicant.class, userid);
        //            docObj.setApplicantid(jobapp);
        docObj.setDocname(fileName);
        //            docObj.setDocdesc(docdesc);
        if (StringUtil.isNullOrEmpty((String) arrparam.get("docdesc")) == false) {
            docObj.setDocdesc((String) arrparam.get("docdesc"));
        }
        docObj.setStorename("");
        docObj.setDoctype(a + " " + "File");
        docObj.setUploadedon(new Date());
        docObj.setUploadedby(uploadedby);
        docObj.setStorageindex(1);
        docObj.setDocsize(fi.getSize() + "");
        docObj.setReferenceid(userid);

        hibernateTemplate.save(docObj);

        String fileid = docObj.getDocid();
        if (Ext.length() > 0) {
            fileid = fileid + Ext;
        }
        docObj.setStorename(fileid);

        hibernateTemplate.update(docObj);

        ll.add(docObj);

        //            String temp = "/home/trainee";
        String temp = storageHandlerImplObj.GetDocStorePath();
        uploadFile(fi, temp, fileid);
    } catch (Exception e) {
        throw ServiceException.FAILURE(e.getMessage(), e);
    }
    return new KwlReturnObject(true, KwlReturnMsg.S01, "", ll, dl);
}

From source file:Index.RegisterRestaurantImagesServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*  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()) {

        String ubicacionArchivo = "C:\\Users\\Romina\\Documents\\NetBeansProjects\\QuickOrderWeb\\web\\images";

        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(1024);
        factory.setRepository(new File(ubicacionArchivo));

        ServletFileUpload upload = new ServletFileUpload(factory);

        try {
            List<FileItem> partes = upload.parseRequest(request);

            List<String> listImage = (List<String>) request.getSession().getAttribute("listImagen");
            if (listImage == null) {
                listImage = new ArrayList<String>();
            }

            for (FileItem item : partes) {
                webservice.Restaurante rest = (webservice.Restaurante) request.getSession()
                        .getAttribute("registroUsuario");
                File file = new File(ubicacionArchivo, rest.getNickname() + listImage.size() + ".jpg");
                item.write(file);
                System.out.println("name: " + item.getName());
                listImage.add(rest.getNickname() + listImage.size() + ".jpg");
            }

            request.getSession().setAttribute("listImagen", listImage);
            request.getRequestDispatcher("/AltaRestauranteImagen.jsp").forward(request, response);
        } catch (FileUploadException ex) {
            System.out.println("Error al subir el archivo: " + ex.getMessage());
            request.getRequestDispatcher("/AltaRestauranteImagen.jsp").forward(request, response);
        } catch (Exception ex) {
            System.out.println("Error al subir el archivo: " + ex.getMessage());
            request.getRequestDispatcher("/AltaRestauranteImagen.jsp").forward(request, response);

        }
    }
}

From source file:com.niconico.mylasta.direction.sponsor.NiconicoMultipartRequestHandler.java

protected void showFileFieldParameter(FileItem item) {
    if (logger.isDebugEnabled()) {
        logger.debug("[param] {}:{name={}, size={}}", item.getFieldName(), item.getName(), item.getSize());
    }/* w  ww  .  j av  a 2  s .  c  o  m*/
}

From source file:com.wellmail.servlet.ConnectorServlet.java

/**
 * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br />
 * //from ww w.j  a  v a  2 s .  c om
 * The servlet accepts commands sent in the following format:<br />
 * <code>connector?Command=&lt;FileUpload&gt;&Type=&lt;ResourceType&gt;&CurrentFolder=&lt;FolderPath&gt;</code>
 * with the file in the <code>POST</code> body.<br />
 * <br>
 * It stores an uploaded file (renames a file if another exists with the
 * same name) and then returns the JavaScript callback.
 */
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    logger.debug("Entering Connector#doPost");

    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html; charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    PrintWriter out = response.getWriter();

    String commandStr = request.getParameter("Command");
    String typeStr = request.getParameter("Type");
    String currentFolderStr = request.getParameter("CurrentFolder");

    logger.debug("Parameter Command: {}", commandStr);
    logger.debug("Parameter Type: {}", typeStr);
    logger.debug("Parameter CurrentFolder: {}", currentFolderStr);

    UploadResponse ur;

    // if this is a QuickUpload request, 'commandStr' and 'currentFolderStr'
    // are empty
    if (Utils.isEmpty(commandStr) && Utils.isEmpty(currentFolderStr)) {
        commandStr = "QuickUpload";
        currentFolderStr = "/";
    }

    if (!RequestCycleHandler.isEnabledForFileUpload(request))
        ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR, null, null,
                Messages.NOT_AUTHORIZED_FOR_UPLOAD);
    else if (!CommandHandler.isValidForPost(commandStr))
        ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_COMMAND);
    else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr))
        ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_TYPE);
    else if (!UtilsFile.isValidPath(currentFolderStr))
        ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
    else {
        ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr);

        String typePath = UtilsFile.constructServerSidePath(request, resourceType);
        String typeDirPath = getServletContext().getRealPath(typePath);

        File typeDir = new File(typeDirPath);
        UtilsFile.checkDirAndCreate(typeDir);

        File currentDir = new File(typeDir, currentFolderStr);

        if (!currentDir.exists())
            ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
        else {

            String newFilename = null;
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            upload.setHeaderEncoding("UTF-8");

            try {

                List<FileItem> items = upload.parseRequest(request);

                // We upload only one file at the same time
                FileItem uplFile = items.get(0);
                String rawName = UtilsFile.sanitizeFileName(uplFile.getName());
                String filename = FilenameUtils.getName(rawName);
                String baseName = FilenameUtils.removeExtension(filename);
                String extension = FilenameUtils.getExtension(filename);

                filename = UUID.randomUUID().toString() + "." + extension;

                if (!ExtensionsHandler.isAllowed(resourceType, extension))
                    ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);

                //20k
                else if (uplFile.getSize() > 100 * 1024) {
                    ur = new UploadResponse(204);
                }

                else {

                    // construct an unique file name
                    File pathToSave = new File(currentDir, filename);
                    int counter = 1;
                    while (pathToSave.exists()) {
                        newFilename = baseName.concat("(").concat(String.valueOf(counter)).concat(")")
                                .concat(".").concat(extension);
                        pathToSave = new File(currentDir, newFilename);
                        counter++;
                    }

                    if (Utils.isEmpty(newFilename))
                        ur = new UploadResponse(UploadResponse.SC_OK,
                                UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr,
                                        true, ConnectorHandler.isFullUrl()).concat(filename));
                    else
                        ur = new UploadResponse(UploadResponse.SC_RENAMED,
                                UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr,
                                        true, ConnectorHandler.isFullUrl()).concat(newFilename),
                                newFilename);

                    // secure image check
                    if (resourceType.equals(ResourceTypeHandler.IMAGE)
                            && ConnectorHandler.isSecureImageUploads()) {
                        if (UtilsFile.isImage(uplFile.getInputStream()))
                            uplFile.write(pathToSave);
                        else {
                            uplFile.delete();
                            ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
                        }
                    } else
                        uplFile.write(pathToSave);

                }
            } catch (Exception e) {
                ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR);
            }
        }

    }

    out.print(ur);
    out.flush();
    out.close();

    logger.debug("Exiting Connector#doPost");
}

From source file:com.lecheng.cms.servlet.ConnectorServlet.java

/**
 * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br />
 * /*  www .  ja v  a  2 s. c  o  m*/
 * The servlet accepts commands sent in the following format:<br />
 * <code>connector?Command=&lt;FileUpload&gt;&Type=&lt;ResourceType&gt;&CurrentFolder=&lt;FolderPath&gt;</code>
 * with the file in the <code>POST</code> body.<br />
 * <br>
 * It stores an uploaded file (renames a file if another exists with the
 * same name) and then returns the JavaScript callback.
 */
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // logger.debug("Entering Connector#doPost");

    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html; charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    PrintWriter out = response.getWriter();

    String commandStr = request.getParameter("Command");
    String typeStr = request.getParameter("Type");
    String currentFolderStr = request.getParameter("CurrentFolder");

    // logger.debug("Parameter Command: {}", commandStr);
    // logger.debug("Parameter Type: {}", typeStr);
    // logger.debug("Parameter CurrentFolder: {}", currentFolderStr);

    UploadResponse ur;

    // if this is a QuickUpload request, 'commandStr' and 'currentFolderStr'
    // are empty
    if (Utils.isEmpty(commandStr) && Utils.isEmpty(currentFolderStr)) {
        commandStr = "QuickUpload";
        currentFolderStr = "/";
    }

    if (!RequestCycleHandler.isEnabledForFileUpload(request))
        ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR, null, null,
                Messages.NOT_AUTHORIZED_FOR_UPLOAD);
    else if (!CommandHandler.isValidForPost(commandStr))
        ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_COMMAND);
    else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr))
        ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_TYPE);
    else if (!UtilsFile.isValidPath(currentFolderStr))
        ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
    else {
        ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr);

        String typePath = UtilsFile.constructServerSidePath(request, resourceType);
        String typeDirPath = getServletContext().getRealPath(typePath);

        File typeDir = new File(typeDirPath);
        UtilsFile.checkDirAndCreate(typeDir);

        File currentDir = new File(typeDir, currentFolderStr);

        if (!currentDir.exists())
            ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
        else {

            String newFilename = null;
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            // FileOperate fo = new FileOperate();//liwei
            // (+ )
            upload.setHeaderEncoding("UTF-8");// liwei 
            try {

                List<FileItem> items = upload.parseRequest(request);

                // We upload only one file at the same time
                FileItem uplFile = items.get(0);
                String rawName = UtilsFile.sanitizeFileName(uplFile.getName());
                String filename = FilenameUtils.getName(rawName);
                String oldName = FilenameUtils.getName(rawName);
                String baseName = FilenameUtils.removeExtension(filename);
                String extension = FilenameUtils.getExtension(filename);
                // filename = fo.generateRandomFilename() +
                // extension;//liwei
                // (+ )
                filename = UUID.randomUUID().toString() + "." + extension;// liwei
                // (UUID)
                // logger.warn(""+oldName+""+filename+"");
                if (!ExtensionsHandler.isAllowed(resourceType, extension))
                    ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
                else {

                    // construct an unique file name
                    File pathToSave = new File(currentDir, filename);
                    int counter = 1;
                    while (pathToSave.exists()) {
                        newFilename = baseName.concat("(").concat(String.valueOf(counter)).concat(")")
                                .concat(".").concat(extension);
                        pathToSave = new File(currentDir, newFilename);
                        counter++;
                    }

                    if (Utils.isEmpty(newFilename))
                        ur = new UploadResponse(UploadResponse.SC_OK,
                                UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr,
                                        true, ConnectorHandler.isFullUrl()).concat(filename));
                    else
                        ur = new UploadResponse(UploadResponse.SC_RENAMED,
                                UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr,
                                        true, ConnectorHandler.isFullUrl()).concat(newFilename),
                                newFilename);

                    // secure image check
                    if (resourceType.equals(ResourceTypeHandler.IMAGE)
                            && ConnectorHandler.isSecureImageUploads()) {
                        if (UtilsFile.isImage(uplFile.getInputStream()))
                            uplFile.write(pathToSave);
                        else {
                            uplFile.delete();
                            ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
                        }
                    } else
                        uplFile.write(pathToSave);

                }
            } catch (Exception e) {
                ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR);
            }
        }

    }

    out.print(ur);
    out.flush();
    out.close();

    // logger.debug("Exiting Connector#doPost");
}

From source file:com.silverpeas.thumbnail.servlets.ThumbnailRequestRouter.java

private String updateFile(List<FileItem> parameters) {
    FileItem item = FileUploadUtil.getFile(parameters, "OriginalFile");
    if (!item.isFormField()) {
        String fileName = FileUtil.getFilename(item.getName());
        if (!FileUtil.isImage(fileName)) {
            return "EX_MSG_WRONG_TYPE_ERROR";
        }//from   w ww .ja  v a 2  s . co m
    } else {
        return "error";
    }

    // parameters seems to be correct -> delete the old thumbnail and create the new one
    String objectId = FileUploadUtil.getParameter(parameters, "ObjectId");
    String componentId = FileUploadUtil.getParameter(parameters, "ComponentId");
    String objectType = FileUploadUtil.getParameter(parameters, "ObjectType");
    ThumbnailDetail thumbToDelete = new ThumbnailDetail(componentId, Integer.parseInt(objectId),
            Integer.parseInt(objectType));
    try {
        ThumbnailController.deleteThumbnail(thumbToDelete);
    } catch (Exception e) {
        return "failed";
    }
    return createThumbnail(parameters);
}