操作文件的工具类:FileUtils.java

该工具类,为本人在项目中所遇问题或所需功能酝酿出来的产物,适应日常情况下的文件上传功能需求。下面把该工具类所需依赖也摆出来。

所需依赖

        <!-- log4j日志依赖 -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.12.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.12.1</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.8.0-beta4</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.8.0-beta4</version>
        </dependency>

        <!-- IO流 -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.2</version>
        </dependency>
        <!-- 文件上传 -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.4</version>
        </dependency>

        <!-- 处理base64格式数据的依赖 -->
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.13</version>
        </dependency>

FileUtils.java

import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 上传文件类
 */
public class FileUtils {

    // 使用日志
    private static Logger logger = Logger.getLogger(FileUtils.class);

    /**
     * 批量处理request中的普通表单项和文件表单项,并返回一个Map集合
     * 该Map集合存储有所有请求参数的值,包括上传文件最终保存文件的文件URL
     * @param request
     * @return
     * @throws Exception
     */
    public static Map<String, Object> uploadFile(HttpServletRequest request) throws Exception {

        logger.info("<<<<<<<<<<<<------- FileUtils类:uploadFile()文件上传方法 -> 开始(" + GeneralUtils.date2Str(new Date()) + ") ------->>>>>>>>>>>>");

        // 创建Map集合用于存储结果集或错误信息
        Map<String, Object> resultMap = new HashMap<String, Object>();
        // 定义MultipartHttpServletRequest类型变量
        MultipartHttpServletRequest multipartHttpServletRequest = null;
        /*
            判断传递进来的参数request是不是属于MultipartHttpServletRequest类型
            判断原因:为了适应SpringBoot和SpringMVC框架
                1. SpringBoot中,请求在进入Controller之前,如果携带有上传文件,
                    则会自动在过滤器中将HttpServletRequest类型的request解析成MultipartHttpServletRequest类型;
                2. SpringMVC中,则不会自动解析。
                因此需要进行判断,再决定是否能够直接强转类型。
         */
        if (request instanceof MultipartHttpServletRequest) {
            // 如果是,则直接将HttpServletRequest类型的request强制转换为MultipartHttpServletRequest类型
            multipartHttpServletRequest = (MultipartHttpServletRequest) request;
        } else {
            // 如果不是,创建CommonsMultipartResolver类型解析器
            CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            /*
                判断当前request是不是包含有enctype="multipart/form-data"属性
                判断原因:主要用于区分第一点和第二点。
                    1. 如果是Swagger页面发送的请求,有文件表单项,但没有选择文件上传
                        那么该request判断的时候,不是enctype="multipart/form-data"类型;
                    2. 如果是前端页面发送请求,因为设置了enctype="multipart/form-data"类型,
                        所以该request是enctype="multipart/form-data"类型,因此无影响。
             */
            boolean flag = commonsMultipartResolver.isMultipart(request);
            if (flag) {
                // 解析HttpServletRequest类型的request为MultipartHttpServletRequest类型
                multipartHttpServletRequest = commonsMultipartResolver.resolveMultipart(request);
            }
        }

        // 如果multipartHttpServletRequest等于null,说明request中不包含上传文件
        if (multipartHttpServletRequest == null) {
            // 保存所有普通表单项的请求参数和参数值
            resultMap.putAll(GeneralUtils.getParameterMap(request));
            logger.info("FileUtils.java ->> uploadFile() ->> 该表单只包含有普通表单项,并不包含有上传文件(" + GeneralUtils.date2Str(new Date()) + ")");
            logger.info("<<<<<<<<<<<<------- FileUtils类:uploadFile()文件上传方法 -> 结束(" + GeneralUtils.date2Str(new Date()) + ") ------->>>>>>>>>>>>");
            // 返回结果集
            return resultMap;
        }

        // 保存所有普通表单项的请求参数和参数值
        resultMap.putAll(GeneralUtils.getParameterMap(multipartHttpServletRequest));

        // 得到存储有所有MultipartFile文件的Map集合
        Map<String, MultipartFile> multipartFileMap = multipartHttpServletRequest.getFileMap();

        // 得到存储有MultipartFile文件的Set集合
        Set<Map.Entry<String, MultipartFile>> set = multipartFileMap.entrySet();

        // 循环遍历得到每一个Entry
        for (Map.Entry<String, MultipartFile> entry : set) {
            // 得到每一个MultipartFile对象
            MultipartFile multipartFile = entry.getValue();

            // 得到文件表单项的name属性的值
            String formFileName = multipartFile.getName();

            // 得到上传文件的原文件名称
            String originalFileName = multipartFile.getOriginalFilename();
//            logger.info("FileUtils.java ->> uploadFile() ->> 当前上传文件的源文件名称 = " + originalFileName);

            // 如果上传文件的原文件名称为空,说明当前的文件输入框没选择上传文件
            if (GeneralUtils.isEmpty(originalFileName)) {
                // 保存对应name属性的属性值为null
                resultMap.put(formFileName, "");
                // 进入下一次循环
                continue;
            }

            // 得到上传文件的后缀及文件类型
            Map<String, Object> getFileSuffixAndFileType_Map = FileUtils.getFileSuffixAndFileType(originalFileName);
            // 获取错误信息
            String errorMsg = (String) getFileSuffixAndFileType_Map.get("errorMsg");
            // 如果错误信息不等于空
            if (GeneralUtils.notEmpty(errorMsg)) {
                logger.info("FileUtils.java ->> uploadFile() ->> 上传文件异常:" + errorMsg + "(" + GeneralUtils.date2Str(new Date()) + ")");
                logger.info("<<<<<<<<<<<<------- FileUtils类:uploadFile()文件上传方法 -> 结束(" + GeneralUtils.date2Str(new Date()) + ") ------->>>>>>>>>>>>");
				resultMap.clear();
                resultMap.put("errorMsg", errorMsg);
                return resultMap;
            }

            // 得到上传文件的后缀
            String uploadFileSuffix = (String) getFileSuffixAndFileType_Map.get("uploadFileSuffix");
            // 得到上传文件的类型
            String uploadFileTypeMark = (String) getFileSuffixAndFileType_Map.get("uploadFileTypeMark");
//            logger.info("FileUtils.java ->> uploadFile() ->> 当前上传文件的文件后缀 = " + uploadFileSuffix);
//            logger.info("FileUtils.java ->> uploadFile() ->> 当前上传文件的文件类型 = " + uploadFileTypeMark);

            // 定义上传文件的文件类型目录
            String uploadFileTypeDir = null;
            // 如果等于image表示是图片
            if ("image".equals(uploadFileTypeMark)) {
                uploadFileTypeDir = "uploadImages";
            } else { // 否则表示其他类型的文件
                uploadFileTypeDir = "uploadFiles";
            }

            // 得到保存文件的前缀路径
            String saveUploadFilePrefixDirectory = FileUtils.getSaveUploadFilePrefixDirectory(request, uploadFileTypeDir);

            // 定义保存文件的日期目录
            String saveUploadFileDateDirectory = GeneralUtils.date2Str(new Date(), "yyyyMMdd");

            // 得到保存文件的完整目录
            File saveUploadFileCompleteDirectory_File = new File(saveUploadFilePrefixDirectory, saveUploadFileDateDirectory);
            // 如果目录不存在的话
            if (! saveUploadFileCompleteDirectory_File.exists()) {
                saveUploadFileCompleteDirectory_File.mkdirs();
            }

//            logger.info("FileUtils.java ->> uploadFile() ->> 最终保存文件的完整目录路径 = " + saveUploadFileCompleteDirectory_File.getPath());

            // 定义保存文件的文件名称,带后缀
            String saveUploadFileName = GeneralUtils.get32UUID() + uploadFileSuffix;

            // 得到保存文件的最终File类型对象
            File saveFile = new File(saveUploadFileCompleteDirectory_File, saveUploadFileName);

            String lastFileName = saveUploadFileName;
            while (saveFile.exists()) {
                lastFileName = GeneralUtils.get32UUID() + uploadFileSuffix;
                saveFile = new File(saveUploadFileCompleteDirectory_File, lastFileName);
            }

//            logger.info("FileUtils.java ->> uploadFile() ->> 最终保存文件的文件名称 = " + lastFileName);

            // 得到MultipartFile中的资源输入流
            InputStream input = multipartFile.getInputStream();

            // 读取输入流中的文件,并通过输出流保存
            FileUtils.inputReadAndOutputWrite(input, saveFile);

            String resultFileName = uploadFileTypeDir + "/" + saveUploadFileDateDirectory + "/" + lastFileName;

//            logger.info("FileUtils.java ->> uploadFile() ->> 最终保存到数据库的文件路径 = " + resultFileName);

            // 保存上传文件最终保存的文件URL到map集合中
            resultMap.put(formFileName, resultFileName);
        }

        logger.info("<<<<<<<<<<<<------- FileUtils类:uploadFile()文件上传方法 -> 结束(" + GeneralUtils.date2Str(new Date()) + ") ------->>>>>>>>>>>>");
        return resultMap;
    }

    /**
     * 根据上传的文件判断文件所属类型及返回文件后缀
     * 文件所属类型:图片或其他
     * @param fileName 文件名称
     * @return
     * @throws Exception
     */
    private static Map<String, Object> getFileSuffixAndFileType(String fileName) throws Exception {

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

        if (GeneralUtils.isEmpty(fileName)) {
            logger.info("FileUtils.java ->> getFileSuffixAndFileType() ->> 错误操作:参数fileName不能为空!(" + GeneralUtils.date2Str(new Date()) + ")");
            throw new RuntimeException("错误操作:参数fileName不能为空!");
        }

        int index = fileName.lastIndexOf(".");

        String uploadFileSuffix = null;
        if (index == -1) {
            logger.info("FileUtils.java ->> getFileSuffixAndFileType() ->> 错误操作:参数fileName(" + fileName + ")不属于文件类型(没有带扩展名)!(" + GeneralUtils.date2Str(new Date()) + ")");
            resultMap.put("mark", false);
            resultMap.put("errorMsg", "错误操作:参数fileName(" + fileName + ")不属于文件类型(没有带扩展名)!");
            return resultMap;
        } else {
            uploadFileSuffix = fileName.substring(index);
        }

        String uploadFileTypeMark = null;
        if (".jpeg".equals(uploadFileSuffix) || ".jpg".equals(uploadFileSuffix)
                || ".png".equals(uploadFileSuffix) || ".gif".equals(uploadFileSuffix)) {
            uploadFileTypeMark = "image";
        } else {
            uploadFileTypeMark = "other";
        }

        resultMap.put("mark", true);
        resultMap.put("uploadFileSuffix", uploadFileSuffix);
        resultMap.put("uploadFileTypeMark", uploadFileTypeMark);

        return resultMap;
    }

    /**
     * 得到用于保存上传文件的前缀路径
     * @param request
     * @param uploadFileTypeDir
     * @return
     * @throws Exception
     */
    private static String getSaveUploadFilePrefixDirectory(HttpServletRequest request, String uploadFileTypeDir) throws Exception {
        // 定义资源输入流,专门用于读取path.properties属性文件
        InputStream pathPropertiesInput = null;
        // 定义用于保存文件的前缀路径
        String saveUploadFilePrefixDirectory = null;
        try {
            // 读取类路径下的path.properties属性文件
            pathPropertiesInput = FileUtils.class.getClassLoader().getResourceAsStream("path.properties");

            // 如果资源输入流不为空
            if (pathPropertiesInput != null) {
                // 定义Properties集合用于读取路径资源输入流
                Properties props = new Properties();
                // 把资源输入流中的属性加载到Properties集合中
                props.load(pathPropertiesInput);

                // 如果Properties集合的长度大于0
                if (props.size() > 0) {
                    // 获取其中的filePath属性的值
                    String filePath = props.getProperty("filePath");

                    // 如果filePath属性的值不为空
                    if (GeneralUtils.notEmpty(filePath)) {

                        // 判断filePath属性的值最后一个字符是否等于 "/"
                        if (filePath.lastIndexOf("/") == (filePath.length() - 1)) {
                            saveUploadFilePrefixDirectory = filePath + uploadFileTypeDir + "/";
                        } else {
                            saveUploadFilePrefixDirectory = filePath + "/" + uploadFileTypeDir + "/";
                        }
                    } else {
                        saveUploadFilePrefixDirectory = request.getServletContext().getRealPath("/static/" + uploadFileTypeDir + "/");
                    }
                } else {
                    saveUploadFilePrefixDirectory = request.getServletContext().getRealPath("/static/" + uploadFileTypeDir + "/");
                }
            } else {
                saveUploadFilePrefixDirectory = request.getServletContext().getRealPath("/static/" + uploadFileTypeDir + "/");
            }
        } catch (Exception e) {
            logger.info("FileUtils.java ->> getSaveUploadFilePrefixDirectory() ->> 异常信息:" + e);
            throw new RuntimeException(e);
        } finally {
            try {
                if (pathPropertiesInput != null) {
                    pathPropertiesInput.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return saveUploadFilePrefixDirectory;
    }

    /**
     * 读取输入流,并通过输出流写出
     * @param input
     * @param file
     * @throws Exception
     */
    public static void inputReadAndOutputWrite(InputStream input, File file) throws Exception {
        // 定义资源输出流,用于将文件输入流写出
        OutputStream saveUploadFileOutput = null;
        try {
            // 关联最终保存文件的File类型对象
            saveUploadFileOutput = new FileOutputStream(file);
            // 定义字节数组,用作缓冲区
            byte[] buf = new byte[1024];
            // 定义int变量记录每次读取到字节数组中的有效长度
            int len = 0;
            // 循环读取
            while ((len = input.read(buf)) != -1) {
                // 写操作
                saveUploadFileOutput.write(buf, 0, len);
            }
            // 刷新
            saveUploadFileOutput.flush();

        } catch (Exception e) {
            logger.info("FileUtils.java ->> inputReadAndOutputWrite() ->> 异常信息:" + e + "(" + GeneralUtils.date2Str(new Date()) + ")");
            throw new RuntimeException(e);
        } finally {
            try {
                if (input != null) {
                    input.close();
                }
                if (saveUploadFileOutput != null) {
                    saveUploadFileOutput.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    /*
        上面是处理 使用enctype="multipart/form-data"上传的文件
    ============================================================================================
        下面是处理 使用base64数据上传的文件
     */


    /**
     * 处理base64上传文件的方法
     * @param request
     * @param paramName
     * @return
     * @throws Exception
     */
    public static Map<String, Object> uploadFile(HttpServletRequest request, String paramName) throws Exception {
        logger.info("========================= FileUtils.java ->> uploadFile()上传文件的方法 ->> 开始(" + GeneralUtils.date2Str(new Date()) + ")=========================");

        Map<String, Object> resultMap = new HashMap<>();
        // 得到base64数据主体
        String base64Data = request.getParameter(paramName);
        logger.info("FileUtils.java ->> uploadFile() ->> 获取到的base64数据 = " + base64Data);
        if (base64Data == null || "".equals(base64Data) || base64Data.trim().isEmpty()) {
            resultMap.put("status", 444);
            resultMap.put("msg", "错误操作:根据指定的请求参数名称获取到的参数为空");
            logger.info("FileUtils.java ->> uploadFile() ->> 错误操作:根据指定的请求参数名称获取到的参数为空");
            logger.info("========================= FileUtils.java ->> uploadFile()上传文件的方法 ->> 结束(" + GeneralUtils.date2Str(new Date()) + ")=========================");
            return resultMap;
        }

        /*
            1,获取到上传文件的扩展名以及文件类别目录
         */
        String prefix = null;
        String dataBody = null;
        if (base64Data.contains("base64,")) {
            String[] strArr = base64Data.split("base64,");
            if (strArr.length == 2) {
                prefix = strArr[0];
                dataBody = strArr[1];
            } else {
                resultMap.put("status", 444);
                resultMap.put("msg", "错误操作:base64数据格式错误");
                logger.info("FileUtils.java ->> uploadFile() ->> 错误操作:base64数据格式错误");
                logger.info("========================= FileUtils.java ->> uploadFile()上传文件的方法 ->> 结束(" + GeneralUtils.date2Str(new Date()) + ")=========================");
                return resultMap;
            }
        }
        logger.info("FileUtils.java ->> uploadFile() ->> 切割得到的数据前缀prefix = " + prefix);
        logger.info("FileUtils.java ->> uploadFile() ->> 切割得到的base64数据主体dataBody = " + dataBody);


        String extensionName = null;
        if (prefix != null) {
            if ("data:text/plain;".equals(prefix)) {
                extensionName = ".txt";
            } else if ("data:application/vnd.ms-excel;".equals(prefix)) {
                extensionName = ".xls";
            } else if ("data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;".equals(prefix)) {
                extensionName = ".xlsx";
            } else if ("data:application/msword;".equals(prefix)) {
                extensionName = ".doc";
            } else if ("data:application/vnd.openxmlformats-officedocument.wordprocessingml.document;".equals(prefix)) {
                extensionName = ".docx";
            } else if ("data:application/vnd.ms-powerpoint;".equals(prefix)) {
                extensionName = ".ppt";
            } else if ("data:application/vnd.openxmlformats-officedocument.presentationml.presentation;".equals(prefix)) {
                extensionName = ".pptx";
            } else if ("data:image/jpeg;".equals(prefix)) {
                extensionName = ".jpeg";
            } else if ("data:image/jpg;".equals(prefix)) {
                extensionName = ".jpg";
            } else if ("data:image/png;".equals(prefix)) {
                extensionName = ".png";
            } else if ("data:image/gif;".equals(prefix)) {
                extensionName = ".gif";
            }
        } else {
            resultMap.put("status", 444);
            resultMap.put("msg", "错误操作:获取文件扩展名错误");
            logger.info("FileUtils.java ->> uploadFile() ->> 错误操作:获取文件扩展名错误");
            logger.info("========================= FileUtils.java ->> uploadFile()上传文件的方法 ->> 结束(" + GeneralUtils.date2Str(new Date()) + ")=========================");
            return resultMap;
        }
        logger.info("FileUtils.java ->> uploadFile() ->> 获取到的文件扩展名extensionName = " + extensionName);

        // 定义上传文件的文件类型目录
        String uploadFileTypeDir = null;
        if (".jpeg".equalsIgnoreCase(extensionName) || ".jpg".equalsIgnoreCase(extensionName)
                || ".png".equalsIgnoreCase(extensionName) || ".gif".equalsIgnoreCase(extensionName)) {
            uploadFileTypeDir = "uploadImages";
        } else {
            uploadFileTypeDir = "uploadFiles";
        }
        logger.info("FileUtils.java ->> uploadFile() ->> 获取到的文件类型目录uploadFileTypeDir = " + uploadFileTypeDir);

        /*
            2,得到保存文件的File对象
         */
        String saveFileRootPath = null;
        InputStream input = null;
        try {
            input = FileUtils.class.getClassLoader().getResourceAsStream("path.properties");
            if (input != null) {
                Properties props = new Properties();
                props.load(input);

                if (props.size() > 0) {
                    String filePath = props.getProperty("filePath");
                    logger.info("FileUtils.java ->> uploadFile() ->> 从path.properties属性文件中读取到的filePath属性 = " + filePath);
                    if (filePath != null && !"".equals(filePath) && !filePath.trim().isEmpty()) {
                        if (filePath.lastIndexOf("/") == (filePath.length() - 1)) {
                            saveFileRootPath = filePath;
                        } else {
                            saveFileRootPath = filePath.concat("/");
                        }
                    } else {
                        saveFileRootPath = request.getServletContext().getRealPath("/static/");
                    }
                } else {
                    saveFileRootPath = request.getServletContext().getRealPath("/static/");
                }
            } else {
                saveFileRootPath = request.getServletContext().getRealPath("/static/");
            }
        } catch (Exception e) {
            logger.info("FileUtils.java ->> uploadFile() ->> 异常信息:" + e);
            logger.info("========================= FileUtils.java ->> uploadFile()上传文件的方法 ->> 结束(" + GeneralUtils.date2Str(new Date()) + ")=========================");
            throw new RuntimeException(e);
        } finally {
            try {
                if (input != null) {
                    input.close();
                    logger.info("FileUtils.java ->> uploadFile() ->> 关闭path.properties属性文件的资源输入流");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        logger.info("FileUtils.java ->> uploadFile() ->> 保存文件的根目录saveFileRootPath = " + saveFileRootPath);

        // 得到保存文件的日期目录
        String saveFileDateDir = new SimpleDateFormat("yyyyMMdd").format(new Date());
        logger.info("FileUtils.java ->> uploadFile() ->> 日期目录saveFileDateDir = " + saveFileDateDir);
        // 得到保存文件的完整目录
        String saveFilePath = saveFileRootPath.concat(uploadFileTypeDir).concat("/").concat(saveFileDateDir);
        logger.info("FileUtils.java ->> uploadFile() ->> 保存文件的完整目录saveFilePath = " + saveFilePath);

        // 不存在则创建目录
        File savePathFile = new File(saveFilePath);
        if (! savePathFile.exists()) {
            savePathFile.mkdirs();
        }

        // 得到保存文件的名称
        String saveFileName = GeneralUtils.get32UUID().concat(extensionName);

        File saveFile = new File(savePathFile, saveFileName);

        while (saveFile.exists()) {
            saveFileName = GeneralUtils.get32UUID().concat(extensionName);
            saveFile = new File(saveFilePath, saveFileName);
        }
        logger.info("FileUtils.java ->> uploadFile() ->> 保存文件的名称saveFileName = " + saveFileName);

        /*
            3,处理base64主体数据并保存上传文件
         */
        OutputStream output = null;
        try {
            output = new FileOutputStream(saveFile);

            byte[] bytes = Base64.decodeBase64(dataBody.getBytes(StandardCharsets.UTF_8));

            // 校验错误数据
            for (int i = 0; i < bytes.length; i++) {
                if (bytes[i] < 0) {
                    bytes[i] += 256;
                }
            }

            output.write(bytes);
            output.flush();

        } catch (Exception e) {
            logger.info("FileUtils.java ->> uploadFile() ->> 异常信息:" + e);
            logger.info("========================= FileUtils.java ->> uploadFile()上传文件的方法 ->> 结束(" + GeneralUtils.date2Str(new Date()) + ")=========================");
            throw new RuntimeException(e);
        } finally {
            try {
                if (output != null) {
                    output.close();
                    logger.info("FileUtils.java ->> uploadFile() ->> 关闭保存文件的资源输出流");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        String result = uploadFileTypeDir.concat("/").concat(saveFileDateDir).concat("/").concat(saveFileName);
        logger.info("FileUtils.java ->> uploadFile() ->> 最终返回的保存文件路径result = " + result);

        resultMap.put("status", 200);
        resultMap.put("data", result);

        logger.info("========================= FileUtils.java ->> uploadFile()上传文件的方法 ->> 结束(" + GeneralUtils.date2Str(new Date()) + ")=========================");
        return resultMap;
    }




    /*
        上面是处理 base64上传文件的方法
        =================================================================================
        下面是其他关于文件的方法
     */




    /**
     * 得到文件在服务器上的访问地址
     * @param fileName
     * @return
     * @throws Exception
     */
    public static String getFileAccessPath(HttpServletRequest request, String fileName) throws Exception {
        InputStream input = null;
        String path = null;
        try {
            if(GeneralUtils.isEmpty(fileName)) {
                logger.info("FileUtils.java ->> getFileAccessPath() ->> 异常信息:文件名称不能为空!(" + GeneralUtils.date2Str(new Date()) + ")");
                throw new RuntimeException("异常信息:文件名称不能为空!");
            }

            input = FileUtils.class.getClassLoader().getResourceAsStream("path.properties");
            if(input != null) {
                Properties props = new Properties();
                props.load(input);

                if(props.size() > 0) {
                    String serverPath = props.getProperty("serverPath");
                    System.out.println("serverPath = " + serverPath);
                    if(GeneralUtils.notEmpty(serverPath)) {
                        if(serverPath.lastIndexOf("/") == (serverPath.length() - 1)) {
                            path = serverPath + fileName;
                        } else {
                            path = serverPath + "/" + fileName;
                        }
                    }
                }
            }

            if(path == null) {
                // 得到保存目录在当前项目中的真实路径
                path = request.getServletContext().getRealPath("/static/") + fileName;
            }

        } catch (Exception e) {
            logger.info("FileUtils.java ->> getFileAccessPath() ->> 异常信息:" + e + "(" + GeneralUtils.date2Str(new Date()) + ")");
            throw new RuntimeException(e);
        } finally {
            try {
                if(input != null) {
                    input.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return path;
    }


    /**
     * 得到文件/文件夹的完整路径
     *  可以得到在服务器上时的文件/文件夹路径
     *  也可以得到在window下项目中的文件/文件夹路径
     * @param request
     * @param fileName
     * @return
     * @throws Exception
     */
    public static String getAbsolutePath(HttpServletRequest request, String fileName) throws Exception {
        InputStream input = null;
        try {
            if(GeneralUtils.isEmpty(fileName)) {
                logger.info("FileUtils.java ->> getAbsolutePath() ->> 异常:文件名称不能为空!(" + GeneralUtils.date2Str(new Date()) + ")");
                throw new RuntimeException("异常:文件名称不能为空!");
            }

            String path = null;
            // 读取属性文件,如果是在服务器上部署,则该文件应该制定有保存文件的路径
            input = GeneralUtils.class.getClassLoader().getResourceAsStream("path.properties");
            if(input != null) {
                Properties props = new Properties();
                props.load(input);

                if(props.size() > 0) {
                    // 读取属性名为filePath的值
                    String filePath = props.getProperty("filePath");
                    // 如果不为空
                    if(filePath != null && ! "".equals(filePath) && !filePath.trim().isEmpty()) {
                        if(filePath.lastIndexOf("/") != (filePath.length() - 1)) {
                            path = filePath + "/" + fileName;
                        } else {
                            path = filePath + fileName;
                        }
                    }
                }
            }

            String contextPath = null;
            // 如果path值为空,说明配置文件中没有指定路径的值
            if(path == null || "".equals(path)) {
                // 手动指定保存目录
                contextPath = "/static/";
                // 得到保存目录在当前项目中的真实路径
                path = request.getServletContext().getRealPath(contextPath) + fileName;
            }

            // 得到path的File对象
            File file = new File(path);
            // 如果file不存在
            if(! file.exists()) {
                logger.info("FileUtils.java ->> getAbsolutePath() ->> 异常:文件在路径下(" + path + ")找不到!(" + GeneralUtils.date2Str(new Date()) + ")");
                throw new RuntimeException("异常:文件在路径下(" + path + ")找不到!");
            }

            return file.getAbsolutePath();

        } catch (Exception e) {
            logger.info("FileUtils.java ->> getAbsolutePath() ->> 异常信息:" + e + "(" + GeneralUtils.date2Str(new Date()) + ")");
            throw new RuntimeException(e);
        } finally {
            try {
                if(input != null) {
                    input.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 删除文件或文件夹
     * @param file
     */
    public static void deleteFile (File file) {

        // 判断文件是否存在
        if(! file.exists()) {
            logger.info("FileUtils.java ->> deleteFile() ->> 错误操作:指定的文件不存在!(" + GeneralUtils.date2Str(new Date()) + ")");
            throw new RuntimeException("错误操作:指定的文件不存在!");
        }
        // 判断file是不是文件夹类型
        if(file.isDirectory()) {
            // 得到文件夹下面的所有文件夹及文件的File对象
            File[] subFiles = file.listFiles();

            if (subFiles != null) {
                // 循环遍历每个File
                for(int i = 0; i < subFiles.length; i++) {
                    // 递归
                    deleteFile(subFiles[i]);
                }
            } else {
                // 删除文件夹
                file.delete();
            }
        } else { // 如果不是则表示属于文件
            // 得到当前文件的父目录
            File parentFile = file.getParentFile();
            // 得到所有的子文件
            File[] subFiles = parentFile.listFiles();

            if (subFiles != null) {
                // 判断父目录下的子文件个数是否等于1
                if(subFiles.length == 1) {
                    // 删除子文件
                    file.delete();
                    // 删除父目录
                    parentFile.delete();
                } else {
                    // 否则说明父目录仍有多个子文件,所以直接删除文件即可
                    file.delete();
                }
            } else {
                file.delete();
            }
        }
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值