Java文件前后端上传下载工具类

  1. 任何非压缩格式下载
package com.pisx.pd.eco.util;

import java.io.*;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.multipart.MultipartFile;

import com.pisx.pd.commom.utils.FileSizeUnitTransform;
import com.pisx.pd.eco.config.FilePathConfig;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class FileUtils {

    public static String downloadFile(HttpServletResponse response, String fileName, String filePath) {
        InputStream inStream = null;
        FileInputStream fis = null;
        ServletOutputStream servletOs = null;
        try {
            // 文件path路径
            File file = new File(filePath, fileName);
            if (file.exists()) {
                response.reset();
                response.setContentType("application/x-msdownload");
                response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
                int fileLength = (int)file.length();
                response.setContentLength(fileLength);
                /* 如果文件长度大于0 */
                if (fileLength != 0) {
                    /* 创建输入流 */
                    fis = new FileInputStream(file);
                    inStream = new BufferedInputStream(fis);
                    byte[] buf = new byte[4096];
                    /* 创建输出流 */
                    servletOs = response.getOutputStream();
                    int readLength;
                    while (((readLength = inStream.read(buf)) != -1)) {
                        servletOs.write(buf, 0, readLength);
                    }
                }
                return "下载成功";
            } else {
                return "文件不存在";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "下载文件出错";
        } finally {
            if (inStream != null) {
                try {
                    fis.close();
                    inStream.close();
                } catch (IOException e) {
                    log.info(e.getMessage());
                }
            }
            if (servletOs != null) {
                try {
                    servletOs.flush();
                    servletOs.close();
                } catch (IOException e) {
                    log.info(e.getMessage());
                }

            }
        }
    }

    public static String downloadFile(HttpServletResponse response, InputStream inputStream, String fileName) {
        ServletOutputStream servletOs = null;
        try {
            response.reset();
            response.setContentType("application/x-msdownload");
            response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            byte[] buf = new byte[4096];
            /* 创建输出流 */
            servletOs = response.getOutputStream();
            int readLength;
            while (((readLength = inputStream.read(buf)) != -1)) {
                servletOs.write(buf, 0, readLength);
            }
            return "下载成功";
        } catch (Exception e) {
            e.printStackTrace();
            return "下载文件出错";
        } finally {
            if (servletOs != null) {
                try {
                    servletOs.flush();
                    servletOs.close();
                } catch (IOException e) {
                    log.info(e.getMessage());
                }

            }
        }
    }

    public static Map<String, String> uploadFile(MultipartFile file, String filePath, String fileName) {
        String fileUrl = filePath + fileName;
        // 获取文件大小
        String fileSize = FileSizeUnitTransform.GetFileSize(file.getSize());
        // 获取文件类型
        int index = fileName.lastIndexOf(".");
        // 文件格式类型
        String fileFormat = fileName.substring(index + 1);
        // 把文件以指定的名字写入指定的路径中
        File filed = new File(FilePathConfig.PATH + fileUrl);
        if (!filed.getParentFile().exists()) {
            boolean mkdirs = filed.getParentFile().mkdirs();
            if (Boolean.FALSE.equals(mkdirs)) {
                return Collections.emptyMap();
            }
        }
        try {
            file.transferTo(filed);
        } catch (Exception ex) {
            log.error(ex.getMessage());
        }
        Map<String, String> map = new HashMap<>(3);
        map.put("fileUrl", fileUrl);
        map.put("fileSize", fileSize);
        map.put("fileFormat", fileFormat);
        return map;
    }

    private FileUtils() {
        throw new IllegalStateException("Utility class");
    }
}

  1. 压缩包格式下载
package com.pisx.pd.eco.util;

import com.pisx.pd.commom.utils.FileSizeUnitTransform;
import com.pisx.pd.datasource.lib.entity.eco.CarbonMore;
import com.pisx.pd.datasource.lib.entity.eco.MineFileDto;
import com.pisx.pd.datasource.lib.entity.eco.StatementTemplate;
import com.pisx.pd.eco.config.FilePathConfig;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Nullable;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class UploadFileUtil {
    static class FileContent {
        // 文件存储路径
        String fileUrl = null;
        // 文件真实名称
        String fileName = null;
        // 文件全路径
        String filePath = null;
        // 获取文件大小
        String fileSize = null;
        // 获取文件类型
        String fileFormat = null;

        public String getFileUrl() {
            return fileUrl;
        }

        public void setFileUrl(String fileUrl) {
            this.fileUrl = fileUrl;
        }

        public String getFileName() {
            return fileName;
        }

        public void setFileName(String fileName) {
            this.fileName = fileName;
        }

        public String getFilePath() {
            return filePath;
        }

        public void setFilePath(String filePath) {
            this.filePath = filePath;
        }

        public String getFileSize() {
            return fileSize;
        }

        public void setFileSize(String fileSize) {
            this.fileSize = fileSize;
        }

        public String getFileFormat() {
            return fileFormat;
        }

        public void setFileFormat(String fileFormat) {
            this.fileFormat = fileFormat;
        }

        public void setExceptFileFormatName(String substring) {}
    }

    public static List<FileContent> uploadFileUtil(MultipartFile[] files, String fileUrl) {
        if (files != null && files.length > 0) {
            try {
                List<FileContent> list = new ArrayList<>();
                for (MultipartFile item : files) {
                    FileContent f = new FileContent();
                    // 文件真实名称
                    f.setFileName(item.getOriginalFilename());
                    // 获取文件大小
                    f.setFileSize(FileSizeUnitTransform.GetFileSize(item.getSize()));
                    // 获取文件类型
                    int index = item.getOriginalFilename().lastIndexOf(".");
                    // 除过文件格式名称
                    f.setExceptFileFormatName(item.getOriginalFilename().substring(0, index));
                    // 文件格式类型
                    f.setFileName(item.getOriginalFilename().substring(index + 1));
                    f.setFileUrl(fileUrl);
                    f.setFilePath(fileUrl + item.getOriginalFilename());
                    list.add(f);
                    // 把文件以指定的名字写入指定的路径中
                    File file = new File(fileUrl + item.getOriginalFilename());
                    if (!file.getParentFile().exists()) {
                        file.getParentFile().mkdirs();
                    }
                }
                return list;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    // 文档下载方法调用的三个静态方法
    public static byte[] getPackage(MineFileDto file) {
        byte[] bag = null;
        try {
            String filePath = file.getFile_path();
            bag = getBytesByFile(filePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bag;
    }

    // 文档下载方法调用的三个静态方法
    public static byte[] getPackageCarbonMore(CarbonMore file) {
        byte[] bag = null;
        try {
            String filePath = file.getFile_path();
            bag = getBytesByFile(filePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bag;
    }

    // 文档下载方法调用的三个静态方法
    public static byte[] getPackages(String filePath) {
        byte[] bag = null;
        try {
            bag = getBytesByFile(filePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bag;
    }

    @Nullable
    private static byte[] getBytesByFile(String filePath) {
        try {
            File file = new File(FilePathConfig.PATH + filePath);
            // 获取输入流
            FileInputStream fis = new FileInputStream(file);
            // 新的 byte 数组输出流,缓冲区容量1024byte
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
            // 缓存
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            // 改变为byte[]
            byte[] data = bos.toByteArray();
            bos.close();
            return data;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void downloadBatchByFile(HttpServletResponse response, Map<String, byte[]> files, String zipName) {
        try {
            response.setContentType("application/x-msdownload");
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(zipName, "UTF-8"));
            ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
            BufferedOutputStream bos = new BufferedOutputStream(zos);
            for (Map.Entry<String, byte[]> entry : files.entrySet()) {
                // 每个zip文件名
                String fileName = entry.getKey();
                // 这个zip文件的字节
                byte[] file = entry.getValue();
                BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(file));
                zos.putNextEntry(new ZipEntry(fileName));
                int len = 0;
                byte[] buf = new byte[10 * 1024];
                while ((len = bis.read(buf, 0, buf.length)) != -1) {
                    bos.write(buf, 0, len);
                }
                bis.close();
                bos.flush();
            }
            bos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值