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:fileserver.Utils.java

/**
 * Save file on disk.// w w w  . jav a2 s  . c  o m
 * Advise: Before, check exist file on disk - isFileExist(FileItem fi).
 * @param fi - uploaded file.
 * @param id - file id
 * @return true - file had saved, false - file not uploaded or error's save on disk.
 */
public static boolean saveFile(FileItem fi, String id) {
    try {
        map.put(id, fi.getName());
        String filePath = dataDirectory + File.separator + fi.getName();
        File uploadedFile = new File(filePath);
        fi.write(uploadedFile);
        return true;
    } catch (Exception ex) {
        logger.error("save file", ex);
        return false;
    }
}

From source file:gov.nist.appvet.shared.FileUtil.java

public static synchronized boolean saveFileUpload(String appId, FileItem fileItem) {
    File file = null;//  ww w.j  a v  a 2 s  .c om
    try {
        final String fileName = getNormalizedFileName(fileItem.getName());
        final String outputFilePath = AppVetProperties.APPS_ROOT + "/" + appId + "/" + fileName;
        file = new File(outputFilePath);
        fileItem.write(file);
        return true;
    } catch (final Exception e) {
        e.printStackTrace();
        log.error(e.getMessage());
        return false;
    } finally {
        file = null;
    }
}

From source file:gov.nih.nci.caintegrator.application.lists.UserListGenerator.java

public static List<String> generateList(FileItem formFile) throws IOException {

    List<String> tempList = new ArrayList<String>();

    if ((formFile != null) && (formFile.getName().endsWith(".txt") || formFile.getName().endsWith(".TXT"))) {

        try {/*from   w  w w  .jav  a 2s  .  com*/
            InputStream stream = formFile.getInputStream();
            String inputLine = null;
            BufferedReader inFile = new BufferedReader(new InputStreamReader(stream));

            do {
                inputLine = inFile.readLine();

                if (inputLine != null) {
                    if (isAscii(inputLine)) { // make sure all data is ASCII                                                        
                        tempList.add(inputLine);
                    }
                } else {
                    System.out.println("null line");
                    while (tempList.contains("")) {
                        tempList.remove("");
                    }
                    inFile.close();
                    break;
                }

            } while (true);
        } catch (EOFException eof) {
            logger.error("Errors when reading empty lines in file:" + eof.getMessage());
        } catch (IOException ex) {
            logger.error("Errors when uploading file:" + ex.getMessage());
        }

    }

    return tempList;

}

From source file:fr.paris.lutece.plugins.directory.utils.JSONUtils.java

/**
 * Builds a json object for the file item list.
 * Key is {@link #JSON_KEY_UPLOADED_FILES}, value is the array of uploaded
 * file./*from  ww w  . j ava2 s.c  o m*/
 * @param listFileItem the fileItem list
 * @return the json
 */
public static JSONObject getUploadedFileJSON(List<FileItem> listFileItem) {
    JSONObject json = new JSONObject();

    if (listFileItem != null) {
        for (FileItem fileItem : listFileItem) {
            json.accumulate(JSON_KEY_UPLOADED_FILES, fileItem.getName());
            json.accumulate(JSON_KEY_UPLOADED_FILES_SIZE, fileItem.getSize());
        }

        json.element(JSON_KEY_FILE_COUNT, listFileItem.size());
    } else {
        // no file
        json.element(JSON_KEY_FILE_COUNT, 0);
    }

    return json;
}

From source file:com.finedo.base.utils.upload.FileUploadUtils.java

public static final List<FileInfo> saveLicense(String uploadDir, List<FileItem> list) {

    List<FileInfo> filelist = new ArrayList<FileInfo>();

    if (list == null) {
        return filelist;
    }/*from w w  w.j  a va2  s  .c  om*/

    //?
    //??
    logger.info("saveFiles uploadDir=============" + uploadDir);
    File dir = new File(uploadDir);
    if (!dir.isDirectory()) {
        dir.mkdirs();
    } else {

    }

    String uploadPath = uploadDir;

    DiskFileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("utf-8");
    Iterator<FileItem> it = list.iterator();
    String name = "";
    String extName = "";

    while (it.hasNext()) {
        FileItem item = it.next();
        if (!item.isFormField()) {
            name = item.getName();
            if (name == null || name.trim().equals("")) {
                continue;
            }
            long l = item.getSize();
            logger.info("file size=" + l);
            if (10 * 1024 * 1024 < l) {
                logger.info("File size is greater than 10M!");
                continue;
            }
            name = name.replace("\\", "/");
            if (name.lastIndexOf("/") >= 0) {
                name = name.substring(name.lastIndexOf("/"));
            }
            logger.info("saveFiles name=============" + name);
            File saveFile = new File(uploadPath + name);
            try {
                item.write(saveFile);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {

            }

            String fileName = item.getName().replace("\\", "/");

            String[] ss = fileName.split("/");
            fileName = trimExtension(ss[ss.length - 1]);
            FileInfo fileinfo = new FileInfo();
            fileinfo.setName(fileName);
            fileinfo.setUname(name);
            fileinfo.setFilePath(uploadDir);
            fileinfo.setFileExt(extName);
            fileinfo.setSize(String.valueOf(item.getSize()));
            fileinfo.setContentType(item.getContentType());
            fileinfo.setFieldname(item.getFieldName());
            filelist.add(fileinfo);
        }
    }
    return filelist;
}

From source file:fr.paris.lutece.plugins.asynchronousupload.util.JSONUtils.java

/**
 * Builds a json object for the file item list.
 * Key is {@link #JSON_KEY_UPLOADED_FILES}, value is the array of uploaded
 * file.// www  . ja v a 2s . c  o  m
 * @param listFileItem the fileItem list
 * @return the json
 */
public static JSONObject getUploadedFileJSON(List<FileItem> listFileItem) {
    JSONObject json = new JSONObject();

    if (listFileItem != null) {
        for (FileItem fileItem : listFileItem) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.element(JSON_KEY_FILE_NAME, fileItem.getName());
            try {

                jsonObject.element(JSON_KEY_FILE_PREVIEW, getPreviewImage(fileItem));

            } catch (IOException e) {

                AppLogService.error(e);
            }
            jsonObject.element(JSON_KEY_FILE_SIZE, fileItem.getSize());
            json.accumulate(JSON_KEY_UPLOADED_FILES, jsonObject);
        }

        json.element(JSON_KEY_FILE_COUNT, listFileItem.size());
    } else {
        // no file
        json.element(JSON_KEY_FILE_COUNT, 0);
    }

    return json;
}

From source file:com.softwarementors.extjs.djn.router.processor.standard.form.upload.UploadFormPostRequestProcessor.java

private static String getFileParametersLogString(Map<String, FileItem> fileFields) {
    StringBuilder result = new StringBuilder();
    for (Map.Entry<String, FileItem> entry : fileFields.entrySet()) {
        FileItem fileItem = entry.getValue();
        String fieldName = entry.getKey();
        result.append(fieldName);//from w  w w  .  java  2 s  . c o  m
        result.append("=");
        String fileName = fileItem.getName();
        result.append(fileName);
        result.append(";");
    }
    return result.toString();
}

From source file:com.finedo.base.utils.upload.FileUploadUtils.java

public static final List<FileInfo> saveFiles(String uploadDir, List<FileItem> list) {

    List filelist = new ArrayList();

    if (list == null) {
        return filelist;
    }/*from   ww w . j  a va 2 s  .com*/

    File dir = new File(uploadDir);
    if (!(dir.isDirectory())) {
        dir.mkdirs();
    }

    String uploadPath = uploadDir;

    DiskFileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("utf-8");
    Iterator it = list.iterator();
    String name = "";
    String extName = "";

    while (it.hasNext()) {
        FileItem item = (FileItem) it.next();
        if (!(item.isFormField())) {
            name = item.getName();
            logger.info("saveFiles name=============" + name);

            if (name == null)
                continue;
            if (name.trim().equals("")) {
                continue;
            }

            if (name.lastIndexOf(".") >= 0) {
                extName = name.substring(name.lastIndexOf("."));
            }

            File file = null;
            do {
                name = UUID.randomUUID().toString();
                file = new File(uploadPath + name + extName);
            } while (file.exists());

            File saveFile = new File(uploadPath + name + extName);
            try {
                item.write(saveFile);
            } catch (Exception e) {
                e.printStackTrace();
            }

            String fileName = item.getName().replace("\\", "/");

            String[] ss = fileName.split("/");
            fileName = trimExtension(ss[(ss.length - 1)]);

            FileInfo fileinfo = new FileInfo();
            fileinfo.setName(fileName);
            fileinfo.setUname(name);
            fileinfo.setFilePath(uploadDir);
            fileinfo.setFileExt(extName);
            fileinfo.setSize(String.valueOf(item.getSize()));
            fileinfo.setContentType(item.getContentType());
            fileinfo.setFieldname(item.getFieldName());
            filelist.add(fileinfo);
        }
    }
    return filelist;
}

From source file:com.founder.fix.fixflow.explorer.util.FileHandle.java

public static String updload(HttpServletRequest request, HttpServletResponse response, String autoPath,
        String showFileName) throws Exception {
    String message = "";

    // ?? //ww  w. j  a va  2 s .  c o m
    File uploadPath = new File(autoPath);
    if (!uploadPath.exists()) {
        uploadPath.mkdir();
    }
    for (int i = 0; i < fi.size(); i++) {
        FileItem fileItem = fi.get(i);
        if (!fileItem.isFormField()) {
            //String fieldName = fileItem.getFieldName(); // ????file  inputname
            String fileName = fileItem.getName(); // file input??
            //String contentType = fileItem.getContentType(); // 
            //long size = fileItem.getSize(); // 

            String filePath = autoPath + File.separator + showFileName;
            // org.apache.commons.fileupload.FileItem ??write?
            // fileItem.write(new File(filePath));
            // ???? ? ?
            OutputStream outputStream = new FileOutputStream(new File(filePath));// ???
            InputStream inputStream = fileItem.getInputStream();
            int length = 0;

            byte[] buf = new byte[1024];
            while ((length = inputStream.read(buf)) != -1) { // ?????
                outputStream.write(buf, 0, length);
            }
            inputStream.close();
            outputStream.close();
            message = "(" + fileName + ")?,??:" + filePath;
        }
    }
    return message;
}

From source file:com.zving.platform.SysInfo.java

public static void uploadDB(HttpServletRequest request, HttpServletResponse response) {
    try {//w  w  w .  j a v a  2 s.c  o  m
        DiskFileItemFactory fileFactory = new DiskFileItemFactory();
        ServletFileUpload fu = new ServletFileUpload(fileFactory);
        List fileItems = fu.parseRequest(request);
        fu.setHeaderEncoding("UTF-8");
        Iterator iter = fileItems.iterator();

        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (!(item.isFormField())) {
                String OldFileName = item.getName();
                System.out.println("Upload DB FileName:" + OldFileName);
                long size = item.getSize();
                if ((((OldFileName == null) || (OldFileName.equals("")))) && (size == 0L)) {
                    continue;
                }
                OldFileName = OldFileName.substring(OldFileName.lastIndexOf("\\") + 1);
                String ext = OldFileName.substring(OldFileName.lastIndexOf("."));
                if (!(ext.toLowerCase().equals(".dat"))) {
                    response.sendRedirect("DBUpload.jsp?Error=?dat?");
                    return;
                }
                final String FileName = Config.getContextRealPath() + "WEB-INF/data/backup/DBUpload_"
                        + DateUtil.getCurrentDate("yyyyMMddHHmmss") + ".dat";
                item.write(new File(FileName));

                LongTimeTask ltt = LongTimeTask.getInstanceByType("Install");
                if (ltt != null) {
                    response.sendRedirect("DBUpload.jsp?Error=??");
                    return;
                }
                SessionListener.forceExit();
                Config.isAllowLogin = false;

                ltt = new LongTimeTask() {
                    public void execute() {
                        DBImport di = new DBImport();
                        di.setTask(this);
                        di.importDB(FileName, "Default");
                        setPercent(100);
                        Config.loadConfig();
                        CronManager.getInstance().init();
                    }
                };
                ltt.setType("Install");
                ltt.setUser(User.getCurrent());
                ltt.start();
                response.sendRedirect("DBUpload.jsp?TaskID=" + ltt.getTaskID());
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        Config.isAllowLogin = true;
    }
}