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

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

Introduction

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

Prototype

String getString();

Source Link

Document

Returns the contents of the file item as a String, using the default character encoding.

Usage

From source file:com.krawler.esp.servlets.importProjectPlanCSV.java

public static String uploadDocument(HttpServletRequest request, String fileid) throws ServiceException {
    String result = "";
    try {//  www  . j a  v  a2s  .  c o  m
        String destinationDirectory = StorageHandler.GetDocStorePath() + StorageHandler.GetFileSeparator()
                + "importplans";
        org.apache.commons.fileupload.DiskFileUpload fu = new org.apache.commons.fileupload.DiskFileUpload();
        org.apache.commons.fileupload.FileItem fi = null;
        org.apache.commons.fileupload.FileItem docTmpFI = null;

        List fileItems = null;
        try {
            fileItems = fu.parseRequest(request);
        } catch (FileUploadException e) {
            KrawlerLog.op.warn("Problem While Uploading file :" + e.toString());
        }

        long size = 0;
        String Ext = "";
        String fileName = null;
        boolean fileupload = false;
        java.io.File destDir = new java.io.File(destinationDirectory);
        fu.setSizeMax(-1);
        fu.setSizeThreshold(4096);
        fu.setRepositoryPath(destinationDirectory);
        java.util.HashMap arrParam = new java.util.HashMap();
        for (java.util.Iterator k = fileItems.iterator(); k.hasNext();) {
            fi = (org.apache.commons.fileupload.FileItem) k.next();
            arrParam.put(fi.getFieldName(), fi.getString());
            if (!fi.isFormField()) {
                size = fi.getSize();
                fileName = new String(fi.getName().getBytes(), "UTF8");

                docTmpFI = fi;
                fileupload = true;
            }
        }

        if (fileupload) {

            if (!destDir.exists()) {
                destDir.mkdirs();
            }
            if (fileName.contains(".")) {
                Ext = fileName.substring(fileName.lastIndexOf("."));
            }
            if (size != 0) {
                File uploadFile = new File(destinationDirectory + "/" + fileid + Ext);
                docTmpFI.write(uploadFile);
                //                    fildoc(fileid, fileName, fileid + Ext, AuthHandler.getUserid(request), size);
                result = fileid + Ext;
            }
        }
    } catch (ConfigurationException ex) {
        Logger.getLogger(importProjectPlanCSV.class.getName()).log(Level.SEVERE, null, ex);
        throw ServiceException.FAILURE("importProjectPlanCSV.uploadDocument", ex);
    } catch (Exception ex) {
        Logger.getLogger(importProjectPlanCSV.class.getName()).log(Level.SEVERE, null, ex);
        throw ServiceException.FAILURE("importProjectPlanCSV.uploadDocument", ex);
    }
    return result;
}

From source file:com.uniquesoft.uidl.servlet.UploadServlet.java

private String formFieldToXml(FileItem i) {
    Map<String, String> item = new HashMap<String, String>();
    item.put(TAG_VALUE, "" + i.getString());
    item.put(TAG_FIELD, "" + i.getFieldName());

    Map<String, String> param = new HashMap<String, String>();
    param.put(TAG_PARAM, statusToString(item));
    return statusToString(param);
}

From source file:com.esteban.cmms.maven.controller.Imagenes_Controller.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//  w  w w . j av a  2s.  c  o  m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String btne = request.getParameter("btn");
    if (btne == null) {
        try {
            HttpSession sesion = request.getSession();
            sesion.removeAttribute("imagenes");
            Usuarios user = (Usuarios) sesion.getAttribute("usuario");
            FileItemFactory itemFactory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(itemFactory);
            String btn = null;
            Maquinas m = new Maquinas();
            List<FileItem> items = upload.parseRequest(request);
            Imagenes pojo = new Imagenes();
            pojo.setUserAction(user.getNombre());

            for (FileItem item : items) {
                if (!item.isFormField()) {
                    String contentType = item.getContentType();
                    if (!contentType.equals("image/png")) { //|| !contentType.equals("image/jpg")
                        continue;
                    }
                    File img = new File(
                            "/home/esteban/NetBeansProjects/"
                                    + "CMMS-Maven/src/main/webapp/Imagenes/images_cli",
                            new Date() + item.getName());
                    item.write(img);
                    pojo.setImagen(img.getName());
                }
                if (item.isFormField()) {
                    if (item.getFieldName().equalsIgnoreCase("maquina")) {
                        int idm = Integer.parseInt(item.getString());
                        System.out.println("Maquina");
                        m.setId(idm);
                        pojo.setMaquinas(m);
                    } else if (item.getFieldName().equalsIgnoreCase("btn")) {
                        System.out.println("Guardar cambios");
                        btn = item.getString().replaceAll("\\s", "");
                    } else if (item.getFieldName().equalsIgnoreCase("id")) {
                        System.out.println("id imagen");
                        pojo.setId(Integer.parseInt(item.getString()));
                    }
                }
            }
            pojo.setEstado("Activo");
            System.out.println("ste es el boton" + btn);
            if (btn.equalsIgnoreCase("actualizar")) {
                new Imagenes_Model().updateImagen(pojo);
            } else {
                new Imagenes_Model().addImagen(pojo);
            }
            response.sendRedirect("Imagenes");

        } catch (FileUploadException ex) {
            System.out.println(ex);
            response.sendRedirect("Static_pages/errores.jsp");
        } catch (Exception ex) {
            System.out.println(ex);
            response.sendRedirect("Static_pages/errores.jsp");
        }
    } else {
        String btn = btne.replaceAll("\\s", "");

        if (btn.equalsIgnoreCase("imagenes")) {
            Imagenes_Model model = new Imagenes_Model();
            HttpSession sesion = request.getSession();
            String valor = request.getParameter("valor");
            List<Imagenes> result = new ArrayList<Imagenes>();
            if (valor.equalsIgnoreCase("activo")) {
                try {
                    result = model.getAllImagenes();
                    sesion.setAttribute("imagenes", result);
                    sesion.setAttribute("maquinas", new Maquinas_Model().getAllMaquinas());

                } catch (Exception e) {
                    System.out.println(e);
                    response.sendRedirect("Static_pages/errores.jsp");
                }
                response.sendRedirect("Imagenes");
            } else if (valor.equalsIgnoreCase("inactivo")) {
                try {
                    result = model.listNoActive();
                    sesion.setAttribute("imagenes", result);

                } catch (Exception e) {
                    System.out.println(e);
                    response.sendRedirect("Static_pages/errores.jsp");
                }
                response.sendRedirect("Imagenes/archivados.jsp");
            }
        } else if (btn.equalsIgnoreCase("estado")) {
            System.out.println("Definicin de estado");
            System.out.println("Nuevo estado: " + request.getParameter("estado"));
            Usuarios user = (Usuarios) request.getSession().getAttribute("usuario");
            try {
                new Imagenes_Model().estadoImagen(request.getParameter("estado"),
                        Integer.parseInt(request.getParameter("id")), user.getNombre());
            } catch (Exception ex) {
                System.out.println(ex);
                response.sendRedirect("Static_pages/errores.jsp");
            }
            System.out.println("Estado definido con xito");
            response.sendRedirect("Imagenes");

        }
    }
}

From source file:edu.isi.pfindr.servlets.QueryServlet.java

/**
 * import the Query URL/*from w w w. ja  v  a 2s .c  o m*/
 * 
 * @param request
 *            the servlet request
 * @param conn
 *            the DB connection
 */
@SuppressWarnings("unchecked")
private void importQuery(HttpServletRequest request, Connection conn) {
    FileItemFactory factory = new DiskFileItemFactory(Integer.MAX_VALUE, null);
    ServletFileUpload upload = new ServletFileUpload(factory);
    HttpSession session = request.getSession();
    try {
        List<FileItem> items = (List<FileItem>) upload.parseRequest(request);
        FileItem item = items.get(0);
        String sql;
        sql = item.getString();
        logger.info("Imported Query: " + sql);
        StringTokenizer tokenizer = new StringTokenizer(sql, "\n\r");
        sql = tokenizer.nextToken();
        JSONObject json = new JSONObject(sql);
        session.setAttribute("query", json);
        logger.info("JSON: " + json.toString());
    } catch (FileUploadException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:it.unisa.tirocinio.servlet.UploadInformationFilesServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//w  ww.j  av  a 2s  .com
 *
 * @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, JSONException {

    try {
        response.setContentType("text/html;charset=UTF-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        out = response.getWriter();
        isMultipart = ServletFileUpload.isMultipartContent(request);
        StudentDBOperation getSerialNumberObj = new StudentDBOperation();
        ConcreteStudent aStudent = null;
        String serialNumber = null;
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List fileItems = upload.parseRequest(request);
        Iterator i = fileItems.iterator();
        File fileToStore = null;
        String studentSubfolderPath = filePath;
        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            if (!fi.isFormField()) {
                // Get the uploaded file parameters
                String fieldName = fi.getFieldName();
                String fileName = fi.getName();
                if (fieldName.equals("cvfile")) {
                    fileToStore = new File(studentSubfolderPath + fileSeparator + "CV.pdf");
                } else if (fieldName.equals("examsfile")) {
                    fileToStore = new File(studentSubfolderPath + fileSeparator + "ES.pdf");
                }
                fi.write(fileToStore);
                // out.println("Uploaded Filename: " + fieldName + "<br>");
            } else {
                //out.println("It's not formfield");
                //out.println(fi.getString());
                aStudent = getSerialNumberObj.getSerialNumberbyFK_Account(Integer.parseInt(fi.getString()));
                serialNumber = reverseSerialNumber(aStudent.getPrimaryKey());
                studentSubfolderPath += fileSeparator + serialNumber;
                new File(studentSubfolderPath).mkdir();
            }
        }
        message.put("status", 1);
        out.print(message.toString());
    } catch (IOException ex) {
        message.put("status", 0);
        message.put("errorMessage", ex);
        out.print(message.toString());
        Logger.getLogger(UploadInformationFilesServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ClassNotFoundException ex) {
        message.put("status", 0);
        message.put("errorMessage", ex);
        out.print(message.toString());
        Logger.getLogger(UploadInformationFilesServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        message.put("status", 0);
        message.put("errorMessage", ex);
        out.print(message.toString());
        Logger.getLogger(UploadInformationFilesServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (FileUploadException ex) {
        message.put("status", 0);
        message.put("errorMessage", ex);
        out.print(message.toString());
        Logger.getLogger(UploadInformationFilesServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        message.put("status", 0);
        message.put("errorMessage", ex);
        out.print(message.toString());
        Logger.getLogger(UploadInformationFilesServlet.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        out.close();
    }
}

From source file:com.sun.licenseserver.License.java

/**
 * Construct a license object using the input provided in the 
 * request object,//from   ww  w.j a v  a 2s .c o m
 * 
 * @param req
 */
public License(HttpServletRequest req) {
    if (FileUpload.isMultipartContent(req)) {
        DiskFileUpload upload = new DiskFileUpload();
        upload.setSizeMax(2 * 1024 * 1024);
        List items;
        try {
            items = upload.parseRequest(req);
        } catch (FileUploadException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return;
        }
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (!item.isFormField()) {
                if (item.getSize() > 2 * 1024 * 1024) {
                    continue;
                }
                m_log.fine("Size of uploaded license is [" + item.getSize() + "]");
                try {
                    license = item.getInputStream();
                    licSize = item.getSize();
                    mime = item.getContentType();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                    return;
                }

            } else {
                String name = item.getFieldName();
                String value = item.getString();
                m_log.fine("MC ItemName [" + name + "] Value[" + value + "]");
                if (name != null) {
                    if (name.equals("id")) {
                        id = value;
                        continue;
                    }
                    if (name.equals("userId")) {
                        userId = value;
                        continue;
                    }
                    if (name.equals("contentId")) {
                        contentId = value;
                        continue;
                    }
                    if (name.equals("shopId")) {
                        shopId = value;
                        continue;
                    }

                }
            }

        }
    }
}

From source file:net.cbtltd.server.UploadFileService.java

/**
 * Handles upload file requests is in a page submitted by a HTTP POST method.
 * Form field values are extracted into a parameter list to set an associated Text instance.
 * 'File' type merely saves file and creates associated db record having code = file name.
 * Files may be rendered by reference in a browser if the browser is capable of the file type.
 * 'Image' type creates and saves thumbnail and full size jpg images and creates associated
 * text record having code = full size file name. The images may be viewed by reference in a browser.
 * 'Blob' type saves file and creates associated text instance having code = full size file name
 * and a byte array data value equal to the binary contents of the file.
 *
 * @param request the HTTP upload request.
 * @param response the HTTP response.//from w ww.ja v  a2 s. co  m
 * @throws ServletException signals that an HTTP exception has occurred.
 * @throws IOException signals that an I/O exception has occurred.
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    ServletRequestContext ctx = new ServletRequestContext(request);

    if (ServletFileUpload.isMultipartContent(ctx) == false) {
        sendResponse(response, new FormResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "The servlet can only handle multipart requests."));
        return;
    }

    LOG.debug("UploadFileService doPost request " + request);

    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);

    LOG.debug("\n doPost upload " + upload);

    SqlSession sqlSession = RazorServer.openSession();
    try {
        HashMap<String, String> params = new HashMap<String, String>();
        for (FileItem item : (List<FileItem>) upload.parseRequest(request)) {
            if (item.isFormField()) { // add for field value to parameter list
                String param = item.getFieldName();
                String value = item.getString();
                params.put(param, value);
            } else if (item.getSize() > 0) { // process uploaded file
                //               String fn = RazorServer.ROOT_DIRECTORY + item.getFieldName();    // input file path
                String fn = RazorConfig.getImageURL() + item.getFieldName(); // input file path
                LOG.debug("doPost fn " + fn);
                byte[] data = item.get();
                String mimeType = item.getContentType();

                String productId = item.getFieldName();
                Pattern p = Pattern.compile("\\d+");
                Matcher m = p.matcher(productId);
                while (m.find()) {
                    productId = m.group();
                    LOG.debug("Image uploaded for Product ID: " + productId);
                    break;
                }

                // TO DO - convert content type to mime..also check if uploaded type is image

                // getMagicMatch accepts Files or byte[],
                // which is nice if you want to test streams
                MagicMatch match = null;
                try {
                    match = parser.getMagicMatch(data, false);
                    LOG.debug("Mime type of image: " + match.getMimeType());
                } catch (MagicParseException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (MagicMatchNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (MagicException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                if (match != null) {
                    mimeType = match.getMimeType();
                }

                // image processor logic needs to know about the format of the image
                String contentType = RazorConfig.getMimeExtension(mimeType);

                if (StringUtils.isNotEmpty(contentType)) {
                    ImageService.uploadImages(sqlSession, productId, item.getFieldName(),
                            params.get(Text.FILE_NOTES), data, contentType);
                    LOG.debug("doPost commit params " + params);
                    sqlSession.commit();
                } else {
                    // unknown content/mime type...do not upload the file
                    sendResponse(response, new FormResponse(HttpServletResponse.SC_BAD_REQUEST,
                            "File type - " + contentType + " is not supported"));
                }
                //               File file = new File(fn);                            // output file name
                //               File tempf = File.createTempFile(Text.TEMP_FILE, "");
                //               item.write(tempf);
                //               file.delete();
                //               tempf.renameTo(file);
                //               int fullsizepixels = Integer.valueOf(params.get(Text.FULLSIZE_PIXELS));
                //               if (fullsizepixels <= 0) {fullsizepixels = Text.FULLSIZE_PIXELS_VALUE;}
                //               int thumbnailpixels = Integer.valueOf(params.get(Text.THUMBNAIL_PIXELS));
                //               if (thumbnailpixels <= 0) {thumbnailpixels = Text.THUMBNAIL_PIXELS_VALUE;}
                //
                //               setText(sqlSession, file, fn, params.get(Text.FILE_NAME), params.get(Text.FILE_TYPE), params.get(Text.FILE_NOTES), Language.EN, fullsizepixels, thumbnailpixels);
            }
        }
        sendResponse(response, new FormResponse(HttpServletResponse.SC_ACCEPTED, "OK"));
    } catch (Throwable x) {
        sqlSession.rollback();
        sendResponse(response, new FormResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, x.getMessage()));
        LOG.error("doPost error " + x.getMessage());
    } finally {
        sqlSession.close();
    }
}

From source file:it.infn.ct.mpi_portlet.java

public void getInputForm(ActionRequest request) {
    if (PortletFileUpload.isMultipartContent(request))
        try {/*  w  w  w . ja v a 2 s  .c o  m*/
            FileItemFactory factory = new DiskFileItemFactory();
            PortletFileUpload upload = new PortletFileUpload(factory);
            List items = upload.parseRequest(request);
            File repositoryPath = new File("/tmp");
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            diskFileItemFactory.setRepository(repositoryPath);
            Iterator iter = items.iterator();
            String logstring = "";
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                String fieldName = item.getFieldName();
                String fileName = item.getName();
                String contentType = item.getContentType();
                boolean isInMemory = item.isInMemory();
                long sizeInBytes = item.getSize();
                logstring += LS + "field name: '" + fieldName + "' - '" + item.getString() + "'";
                switch (inputControlsIds.valueOf(fieldName)) {
                case file_inputFile:
                    inputFileName = item.getString();
                    processInputFile(item);
                    break;
                case inputFile:
                    inputFileText = item.getString();
                    break;
                case JobIdentifier:
                    jobIdentifier = item.getString();
                    break;
                case cpunumber:
                    cpunumber = item.getString();
                    break;
                default:
                    _log.info("Unhandled input field: '" + fieldName + "' - '" + item.getString() + "'");
                } // switch fieldName                                                   
            } // while iter.hasNext()   
            _log.info(LS + "Reporting" + LS + "---------" + LS + logstring);
        } catch (Exception e) {
            _log.info("Caught exception while processing files to upload: '" + e.toString() + "'");
        }
    // The input form do not use the "multipart/form-data" 
    else {
        // Retrieve from the input form the given application values
        inputFileName = (String) request.getParameter("file_inputFile");
        inputFileText = (String) request.getParameter("inputFile");
        jobIdentifier = (String) request.getParameter("JobIdentifier");
        cpunumber = (String) request.getParameter("cpunumber");
    } // ! isMultipartContent

    // Show into the log the taken inputs
    _log.info(LS + "Taken input parameters:" + LS + "inputFileName: '" + inputFileName + "'" + LS
            + "inputFileText: '" + inputFileText + "'" + LS + "jobIdentifier: '" + jobIdentifier + "'" + LS
            + "cpunumber: '" + cpunumber + "'");
}

From source file:controllers.controller.java

private void subirArchivo(HttpSession session, HttpServletRequest request, HttpServletResponse response,
        QUID quid, PrintWriter out) throws Exception {
    String FormFrom = "";
    if (ServletFileUpload.isMultipartContent(new ServletRequestContext(request))) {
        System.out.println("Tamao del archivo: " + request.getContentLength());
        if (PageParameters.getParameter("fileSizeLimited").equals("1") && (request.getContentLength() == -1//Este valor aparece cuando se desconoce el tamano
                || request.getContentLength() > Integer
                        .parseInt(PageParameters.getParameter("maxSizeToUpload")))) {
            this.getServletConfig().getServletContext().getRequestDispatcher(""
                    + PageParameters.getParameter("msgUtil")
                    + "/msgNBack.jsp?title=Error&type=error&msg=El tamao mximo del archivo es de "
                    + StringUtil.formatDouble1Decimals(
                            Double.parseDouble(PageParameters.getParameter("maxSizeToUpload")) / 1048576)
                    + " MBytes.").forward(request, response);
        } else {// w w  w.  j  a v  a  2s . c o  m

            ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
            List items = upload.parseRequest(request);
            Iterator i = items.iterator();
            LinkedList filesToUpload = new LinkedList();
            HashMap parameters = new HashMap();
            while (i.hasNext()) {
                FileItem item = (FileItem) i.next();
                if (item.isFormField()) {
                    if (item.getFieldName().equalsIgnoreCase("FormFrom")) {
                        FormFrom = item.getString();
                    } else {
                        parameters.put(item.getFieldName(), item.getString());
                    }
                } else {
                    filesToUpload.add(item);
                }
            }
            switch (FormFrom) {

            case "insertObjetoArchivo":
                this.insertarObjetoArchivo(session, request, response, quid, out, parameters, filesToUpload,
                        FormFrom);
                break;
            }
        }
    }
}

From source file:com.jflyfox.modules.filemanager.FileManager.java

public JSONObject add() {
    Iterator<?> it = this.files.iterator();
    if (!it.hasNext()) {
        this.error(lang("INVALID_FILE_UPLOAD"));
        return null;
    }/*from ww  w  .  ja v a 2 s  .  c  o m*/

    JSONObject fileInfo = null;
    Map<String, String> params = new HashMap<String, String>();
    File tmpFile = null;
    boolean error = false;

    // file field operate
    try {
        FileItem item = null;
        while (it.hasNext()) {
            item = (FileItem) it.next();
            if (item.isFormField()) {
                params.put(item.getFieldName(), item.getString());
            } else {
                params.put("_fileFieldName", item.getFieldName());
                params.put("_fileName", item.getName());
                params.put(item.getFieldName(), item.getName());

                long maxSize = NumberUtils.parseLong(MAX_SIZE);
                if (getConfig("upload-size") != null) {
                    maxSize = Integer.parseInt(getConfig("upload-size"));
                    if (maxSize != 0 && item.getSize() > (maxSize * 1024 * 1024)) {
                        this.error(sprintf(lang("UPLOAD_FILES_SMALLER_THAN"), maxSize + "Mb"));
                        error = true;
                    }
                }

                if (!isImage(item.getName()) && (getConfig("upload-imagesonly") != null
                        && getConfig("upload-imagesonly").equals("true")
                        || this.params.get("type") != null && this.params.get("type").equals("Image"))) {
                    this.error(lang("UPLOAD_IMAGES_ONLY"));
                    error = true;
                }

                if (error) {
                    break;
                }

                tmpFile = new File(
                        this.fileRoot + TMP_PATH + "filemanager_" + System.currentTimeMillis() + ".tmp");
                File filePath = tmpFile.getParentFile();
                if (!filePath.exists()) {
                    filePath.mkdirs();
                }
                item.write(tmpFile);
            }
        }

    } catch (Exception e) {
        logger.error("INVALID_FILE_UPLOAD", e);
        this.error(lang("INVALID_FILE_UPLOAD"));
    }

    // file rename
    try {
        if (!error && tmpFile != null) {
            String allowed[] = { ".", "-" };

            if ("add".equals(params.get("mode"))) {
                fileInfo = new JSONObject();
                String respPath = "";

                String currentPath = "";
                String fileName = params.get("_fileName");
                String filePath = "";
                try {
                    currentPath = params.get("currentpath");
                    respPath = currentPath;
                    currentPath = new String(currentPath.getBytes("ISO8859-1"), "UTF-8"); // ?
                    currentPath = getFilePath(currentPath);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                filePath = FileManagerUtils.rebulid(this.fileRoot + currentPath);

                LinkedHashMap<String, String> strList = new LinkedHashMap<String, String>();
                strList.put("fileName", fileName);
                fileName = (String) cleanString(strList, allowed).get("fileName");

                if (getConfig("upload-overwrite").equals("false")) {
                    fileName = this.checkFilename(filePath, fileName, 0);
                }

                File saveFile = new File(filePath + fileName);
                tmpFile.renameTo(saveFile);

                fileInfo.put("Path", respPath);
                fileInfo.put("Name", fileName);
                fileInfo.put("Error", "");
                fileInfo.put("Code", 0);
            } else if ("replace".equals(params.get("mode"))) {
                fileInfo = new JSONObject();
                String respPath = "";

                String fileName = "";
                String newFilePath = "";
                String saveFilePath = "";

                try {
                    newFilePath = params.get("newfilepath");
                    newFilePath = new String(newFilePath.getBytes("ISO8859-1"), "UTF-8"); // ?
                    respPath = newFilePath.substring(0, newFilePath.lastIndexOf("/") + 1);
                    fileName = newFilePath.substring(newFilePath.lastIndexOf("/") + 1);
                    newFilePath = getFilePath(newFilePath);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }

                saveFilePath = FileManagerUtils.rebulid(this.fileRoot + newFilePath);
                File saveFile = new File(saveFilePath);

                LinkedHashMap<String, String> strList = new LinkedHashMap<String, String>();
                strList.put("fileName", fileName);
                fileName = (String) cleanString(strList, allowed).get("fileName");

                if (getConfig("upload-overwrite").equals("false")) {
                    fileName = this.checkFilename(saveFile.getParent(), fileName, 0);
                }

                if (saveFile.exists()) {
                    // before bakup
                    bakupFile(saveFile);
                    // delete src file
                    saveFile.delete();
                }

                tmpFile.renameTo(saveFile);

                fileInfo.put("Path", respPath);
                fileInfo.put("Name", fileName);
                fileInfo.put("Error", "");
                fileInfo.put("Code", 0);
            } else {
                this.error(lang("INVALID_FILE_UPLOAD"));
            }

        }
    } catch (Exception e) {
        logger.error("INVALID_FILE_UPLOAD", e);
        this.error(lang("INVALID_FILE_UPLOAD"));
    }

    // ?
    if (tmpFile.exists()) {
        tmpFile.delete();
    }

    return fileInfo;

}