FileUtils

#FileUtils

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

/**
 * @program: freeter-coding
 * @description: 文件上传(支持单文件上传和多文件上传)
 *              1.1版本:新增上传文件后返回字符串路径
 *              1.2版本:新增文件上传,返回文件名,文件后缀名,文件上传路径,文件下载(未测试)
 * @create: 2018-12-12 13:52
 **/
public class FileUtils implements Serializable {

    //文件路径
    private String dir;


    public String getDir() {
        return dir;
    }
    public void setDir(String dir) {
        this.dir = dir;
    }

    public FileUtils() {}

    public FileUtils(String dir) {
        this.dir = dir;
    }

    public LinkedHashMap<String,Object> fileUploadOne(MultipartFile file, String dir){
        String fileDir = dir;
        LinkedHashMap<String,Object> list = new LinkedHashMap<String,Object>();
        // 判断文件是否有内容
        if (file.isEmpty()){
            list.put("error","该文件无任何内容");
            return list;
        }
        //获取附件原名
        String fileName = file.getOriginalFilename();
        //如果是获取的含有路径的文件名, 那么截取掉多余的,只剩下文件名和后缀名
        int index = fileName.lastIndexOf("\\");
        if(index > 0){
            fileName = fileName.substring(index + 1);
        }
        long fileSize = file.getSize();
        if(fileSize != 0){
            //判断文件有后缀名时
            if(fileName.indexOf(".") >= 0){
                //split()中放正则表达式;转义符“\\”代表"."
                String[] fileNameSplit = fileName.split("\\.");
                //加上reandom戳,防止文件重名覆盖原文件
                fileName = fileNameSplit[0] + UUID.randomUUID() + "." + fileNameSplit[1];
            }
            //当文件无后缀名时
            if(fileName.indexOf(".") < 0){
                //加上reandom戳,防止文件重名覆盖原文件
                fileName = fileName + UUID.randomUUID();
            }
            //根据文件的完全路径(含路径,后缀),new 一个file对象dest
            File dest = new File(fileDir + fileName);
            //如果该文件的上级文件夹不存在, 则创建文件的上级文件夹和其祖辈级文件夹
            if(!dest.getParentFile().exists()){
                dest.getParentFile().mkdirs();
            }
            try {
                String name = fileDir + fileName;
                list.put("data",name);
                //获取到的附件file, transferTo写入到指定的位置(即: 创建dest时, 指定的路径)
                file.transferTo(dest);
                return list;
            }catch (IllegalStateException e){
                e.printStackTrace();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
        list.put("error","上传失败");
        return list;
    }

    public LinkedHashMap<Object,Object> fileUploadMore(MultipartFile[] files,String dir){
        LinkedHashMap<Object,Object> list = new LinkedHashMap<Object,Object>();
        try{
            //上传目录地址
            String fileDir = dir;
            //如果目录不存在
            File file = new File(fileDir);
            if (!file.exists()){
                file.mkdir();
            }
            //遍历文件数组执行上传
            for (int i = 0;i < files.length;i++){
                if(files[i] != null){
                    //调用
                    Map<String,Object> map = new FileUtils().executeUpload(dir,files[i]);
                    list.put(i,map);
                }
            }
            return list;
        }catch (Exception e){
            e.printStackTrace();
        }
        list.put("error","上传失败");
        return list;
    }

    //上传的公共方法
    private Map<String,Object> executeUpload(String uploadDir, MultipartFile file) throws Exception{
        Map<String,Object> list = new LinkedHashMap<String,Object>();
        //文件后缀名
        String str = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        //上传文件名
        String filename = UUID.randomUUID() + str;
        //服务器端保存文件对象
        File serverFile = new File(uploadDir + filename);
        //将上传的文件写入到服务器端文件内;
        file.transferTo(serverFile);
        list.put("data",uploadDir + filename);
        return list;
    }

    //传入多个文件, 返回地址
    public String pathStrings(MultipartFile[] file,String dir){
        String imgPath = "";
        LinkedHashMap map = new FileUtils().fileUploadMore(file,dir);
       if(map.size() != 0){
           for (int i = 0; i < map.size();i++ ){
               Object obj = map.get(i);
               imgPath += obj.toString().substring(obj.toString().lastIndexOf("=")+1,obj.toString().lastIndexOf("}")) + ";";
           }
       }
        return imgPath;
    }

    //传入一个文件, 返回地址
    public String pathString(MultipartFile file,String dir){
        String imgPath = "";
        LinkedHashMap map = new FileUtils().fileUploadOne(file,dir);
        imgPath += map.toString().substring(map.toString().lastIndexOf("=")+1,map.toString().lastIndexOf("}")) + ";";
        return imgPath;
    }


    private ArrayList<Object> UploadPaths(String uploadDir, MultipartFile file) throws Exception{
        ArrayList<Object> arrayList = new ArrayList<Object>();
        //文件后缀名
        String str = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));

        //上传文件名
        String filename = UUID.randomUUID() + str;
        arrayList.add(filename);
        arrayList.add(str);
        arrayList.add(uploadDir);
        //服务器端保存文件对象
        File serverFile = new File(uploadDir + filename);
        //将上传的文件写入到服务器端文件内;
        file.transferTo(serverFile);
        return arrayList;
    }


    //传入一个文件, 返回 文件名, 文件后缀名 , 文件存储路径 ,文件大小
    public ArrayList Paths(MultipartFile[] files,String dir){
        ArrayList list = new ArrayList();
        try{
            //上传目录地址
            String fileDir = dir;
            //如果目录不存在
            File file = new File(fileDir);
            if (!file.exists()){
                file.mkdir();
            }
            //遍历文件数组执行上传
            for (int i = 0;i < files.length;i++){
                //调用
                ArrayList<Object> arrayList = new FileUtils().UploadPaths(dir,files[i]);
                list.add(arrayList);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return list;
    }

    //文件下载  !!! 未测试X
    public void download(HttpServletResponse response, String filePath)throws RuntimeException{
        File file = new File(filePath);
        if(!file.exists()){
            throw new RuntimeException("文件不存在");
        }
        BufferedInputStream bin = null;
        BufferedOutputStream bout = null;
        try {
            //缓存流
            bin = new BufferedInputStream(new FileInputStream(file));
            bout = new BufferedOutputStream(response.getOutputStream());
            byte[] b = new byte[1024 * 5];// 缓存数组
            int len = 0;
            while ((len = bin.read(b)) != -1){
                bout.write(b, 0, len);
                bout.flush();
            }
        }catch (FileNotFoundException  e){
            e.printStackTrace();
            throw new RuntimeException("文件读取异常");
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("文件读取异常");
        }finally {
            try{
                // 关闭缓存流的时候会将输入输出流给关闭
                if (bin != null){
                    bin.close();
                }
                if (bout != null){
                    bout.close();
                }
            }
            catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException("文件读取异常");
            }
        }
    }

    /**
     * @param request
     * @param response
     * @param downloadFile 下载文件完整路径
     * @param fileName 下载文件名(带文件后缀)
     */
    //未测试 X
    public static void downloadFile(HttpServletRequest request, HttpServletResponse response, String downloadFile, String fileName) {

        BufferedInputStream bis = null;
        InputStream is = null;
        OutputStream os = null;
        BufferedOutputStream bos = null;
        try {
            File file=new File(downloadFile); //:文件的声明
            is = new FileInputStream(file);  //:文件流的声明
            os = response.getOutputStream(); // 重点突出
            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(os);

            if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0) {
                fileName = new String(fileName.getBytes("GB2312"),"ISO-8859-1");
            } else {
                // 对文件名进行编码处理中文问题
                fileName = java.net.URLEncoder.encode(fileName, "UTF-8");// 处理中文文件名的问题
                fileName = new String(fileName.getBytes("UTF-8"), "GBK");// 处理中文文件名的问题
            }

            response.reset(); // 重点突出
            response.setCharacterEncoding("UTF-8"); // 重点突出
            response.setContentType("application/x-msdownload");// 不同类型的文件对应不同的MIME类型 // 重点突出
            // inline在浏览器中直接显示,不提示用户下载
            // attachment弹出对话框,提示用户进行下载保存本地
            // 默认为inline方式
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
            //  response.setHeader("Content-Disposition", "attachment; filename="+fileName); // 重点突出
            int bytesRead = 0;
            byte[] buffer = new byte[4096];// 4k或者8k
            while ((bytesRead = bis.read(buffer)) != -1){ //重点
                bos.write(buffer, 0, bytesRead);// 将文件发送到客户端
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            // 特别重要
            // 1. 进行关闭是为了释放资源
            // 2. 进行关闭会自动执行flush方法清空缓冲区内容
            try {
                if (null != bis) {
                    bis.close();
                    bis = null;
                }
                if (null != bos) {
                    bos.close();
                    bos = null;
                }
                if (null != is) {
                    is.close();
                    is = null;
                }
                if (null != os) {
                    os.close();
                    os = null;
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    /**
     * 文件下载
     * @param response
     * @param downloadFile 文件的路径
     * @param showFileName 下载后显示的文件名称
     */
    // 未测试
    public static void downloadFile(HttpServletResponse response, String downloadFile, String showFileName) {

        BufferedInputStream bis = null;
        InputStream is = null;
        OutputStream os = null;
        BufferedOutputStream bos = null;
        try {
            File file=new File(downloadFile); //:文件的声明
            String fileName=file.getName();
            is = new FileInputStream(file);  //:文件流的声明
            os = response.getOutputStream(); // 重点突出
            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(os);
            // 对文件名进行编码处理中文问题
            fileName = java.net.URLEncoder.encode(showFileName, "UTF-8");// 处理中文文件名的问题
            fileName = new String(fileName.getBytes("UTF-8"), "GBK");// 处理中文文件名的问题
            response.reset(); // 重点突出
            response.setCharacterEncoding("UTF-8"); // 重点突出
            response.setContentType("application/x-msdownload");// 不同类型的文件对应不同的MIME类型 // 重点突出
            // inline在浏览器中直接显示,不提示用户下载
            // attachment弹出对话框,提示用户进行下载保存本地
            // 默认为inline方式
            response.setHeader("Content-Disposition", "attachment; filename="+fileName); // 重点突出
            int bytesRead = 0;
            byte[] buffer = new byte[1024];
            while ((bytesRead = bis.read(buffer)) != -1){ //重点
                bos.write(buffer, 0, bytesRead);// 将文件发送到客户端
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            throw new RuntimeException(ex.getMessage());
        } finally {
            // 特别重要
            // 1. 进行关闭是为了释放资源
            // 2. 进行关闭会自动执行flush方法清空缓冲区内容
            try {
                if (null != bis) {
                    bis.close();
                    bis = null;
                }
                if (null != bos) {
                    bos.close();
                    bos = null;
                }
                if (null != is) {
                    is.close();
                    is = null;
                }
                if (null != os) {
                    os.close();
                    os = null;
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                throw new RuntimeException(ex.getMessage());
            }
        }
    }

}

个人博客地址: www.yaoguanquan.top

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

饭酱

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值