UploadUtil导入工具类

本文档介绍如何利用UploadUtil工具类进行文件上传操作,包括导入步骤和使用示例,帮助开发者高效处理文件上传任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.common.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class UploadUtil {

    private static String uploadPath;

    @Value("${upload.path}")
    public void setUploadPath(String uploadPath) {
        UploadUtil.uploadPath = uploadPath;
    }

    /**
     * 上传文件
     *
     * @param applicationName
     * @param file
     * @return
     */
    public static Map upload(String applicationName, MultipartFile file) {
        Map map = new HashMap();
        String fileName = file.getOriginalFilename();
        map.put("name", fileName);

        String type = fileName.substring(fileName.lastIndexOf("."));
        fileName = new Date().getTime() + type;
        File dest = new File(uploadPath + applicationName + "/" + fileName);
        if (!dest.getParentFile().exists()) { // 判断文件父目录是否存?
            dest.getParentFile().mkdirs();
        }
        map.put("type", type);
        map.put("filePath", applicationName + "/" + fileName);
        map.put("localFilePath", uploadPath + applicationName + "/" + fileName);

        try {
            file.transferTo(dest); // 保存文件
        } catch (IllegalStateException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return map;
    }


    /**
     * 复制单个文件
     *
     * @param oldPath String 原文件路? 如:c:/fqf.txt
     * @param newPath String 复制后路? 如:f:/fqf.txt
     * @return boolean
     */
    @SuppressWarnings({"unused", "resource"})
    public static void copyFile(String oldPath, String newPath) {
        InputStream inStream = null;
        FileOutputStream fs = null;
        try {
            int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldPath);
            if (oldfile.exists()) { // 文件存在?
                inStream = new FileInputStream(oldPath); // 读入原文?
                fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1444];
                int length;
                while ((byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread; // 字节? 文件大小
                    fs.write(buffer, 0, byteread);
                }

            }
        } catch (Exception e) {
            System.out.println("复制单个文件操作出错");
            e.printStackTrace();

        } finally {
            try {
                inStream.close();
                fs.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }

    /**
     * 复制整个文件夹内?
     * 加一个map 里面放所有的匹配到的文件名集合 然后通过路径对比拿原文件名字
     *
     * @param oldPath String 原文件路? 如:c:/fqf
     * @param newPath String 复制后路? 如:f:/fqf/ff
     * @return boolean
     */
    public static void copyFolder(String oldPath, String newPath, Map<String, String> map, String url) {
        FileInputStream input = null;
        FileOutputStream output = null;
        try {
            (new File(newPath)).mkdirs(); // 如果文件夹不存在 则建立新文件?
            File a = new File(oldPath);
            String[] file = a.list();
            File temp = null;
            for (int i = 0; i < file.length; i++) {
                String spath = "";
                if (oldPath.endsWith(File.separator)) {
                    temp = new File(oldPath + file[i]);
                    spath = oldPath + file[i];
                } else {
                    temp = new File(oldPath + File.separator + file[i]);
                    spath = oldPath + "/" + file[i];
                }

                if (temp.isFile()) {
                    input = new FileInputStream(temp);
                    String path = "";

                    if (spath != null && !spath.equals("")) {
                        path = spath;
                    } else {
                        path = (temp.getName()).toString();
                    }
                    path = path.replace(url, "");
                    output = new FileOutputStream(newPath + "/" + map.get("/" + path));
                    byte[] b = new byte[1024 * 5];
                    int len;
                    while ((len = input.read(b)) != -1) {
                        output.write(b, 0, len);
                    }
                    output.flush();

                }
                if (temp.isDirectory()) {// 如果是子文件?
                    copyFolder(oldPath + "/" + file[i], newPath + "/" + file[i], map, url);
                }
            }
        } catch (Exception e) {
            System.out.println("复制整个文件夹内容操作出?");
            e.printStackTrace();

        } finally {

            try {
                output.close();
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 复制整个文件夹内?
     * 加一个map 里面放所有的匹配到的文件名集合 然后通过路径对比拿原文件名字
     *
     * @param oldPath String 原文件路? 如:c:/fqf
     * @param newPath String 复制后路? 如:f:/fqf/ff
     * @return boolean
     */
    public static void copyFolder(String oldPath, String newPath) {
        FileInputStream input = null;
        FileOutputStream output = null;
        try {
            (new File(newPath)).mkdirs(); // 如果文件夹不存在 则建立新文件?
            File a = new File(oldPath);
            String[] file = a.list();
            File temp = null;
            for (int i = 0; i < file.length; i++) {
                if (oldPath.endsWith(File.separator)) {
                    temp = new File(oldPath + file[i]);
                } else {
                    temp = new File(oldPath + File.separator + file[i]);
                }

                if (temp.isFile()) {
                    input = new FileInputStream(temp);
                    output = new FileOutputStream(newPath + "/" + (temp.getName()).toString());
                    byte[] b = new byte[1024 * 5];
                    int len;
                    while ((len = input.read(b)) != -1) {
                        output.write(b, 0, len);
                    }
                    output.flush();

                }
                if (temp.isDirectory()) {// 如果是子文件?
                    copyFolder(oldPath + "/" + file[i], newPath + "/" + file[i]);
                }
            }
        } catch (Exception e) {
            System.out.println("复制整个文件夹内容操作出?");
            e.printStackTrace();

        } finally {
            try {
                output.close();
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 删除单个文件
     *
     * @param sPath 被删除文件的文件?
     * @return 单个文件删除成功返回true,否则返回false
     */
    public static boolean deleteFile(String sPath, HttpServletRequest request) {
        //String path = request.getSession().getServletContext().getRealPath("/");
        boolean flag = false;
        File file = new File(sPath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }

    /**
     * 删除目录及目录下的文件
     *
     * @param dir 要删除的目录的文件路径
     * @return 目录删除成功返回true,否则返回false
     */
    public static boolean deleteDirectory(String dir, HttpServletRequest request) {
        // 如果dir不以文件分隔符结尾,自动添加文件分隔符
        if (!dir.endsWith(File.separator))
            dir = dir + File.separator;
        File dirFile = new File(dir);
        // 如果dir对应的文件不存在,或者不是一个目录,则退出
        if ((!dirFile.exists()) || (!dirFile.isDirectory())) {
            System.out.println("删除目录失败:" + dir + "不存在!");
            return false;
        }
        boolean flag = true;
        // 删除文件夹中的所有文件包括子目录
        File[] files = dirFile.listFiles();
        for (int i = 0; i < files.length; i++) {
            // 删除子文件
            if (files[i].isFile()) {
                flag = deleteFile(files[i].getAbsolutePath(), request);
                if (!flag)
                    break;
            }
            // 删除子目录
            else if (files[i].isDirectory()) {
                flag = deleteDirectory(files[i]
                        .getAbsolutePath(), request);
                if (!flag)
                    break;
            }
        }
        if (!flag) {
            System.out.println("删除目录失败!");
            return false;
        }
        // 删除当前目录
        if (dirFile.delete()) {
            System.out.println("删除目录" + dir + "成功!");
            return true;
        } else {
            return false;
        }
    }

    /**
     * 移动文件到指定目录
     *
     * @param oldPath String  如:c:/fqf.txt
     * @param newPath String  如:d:/fqf.txt
     */
    public static void moveFile(String oldPath, String newPath, HttpServletRequest request) {
        copyFile(oldPath, newPath);
        deleteFile(oldPath, request);

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值