文件工具类(路径转MultipartFile,读取文件内容,通用文件上传,通用文件下载)

package com.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Scanner;

@Slf4j
public class FileUtils {

    /* 文件路径 转  MultipartFile*/
    public static MultipartFile getMultipartFile(String filePath) {
        File file = new File(filePath);
        FileItem item = new DiskFileItemFactory().createItem(file.getName(), MediaType.MULTIPART_FORM_DATA_VALUE, true, file.getName());
        try {
            InputStream input = new FileInputStream(file);
            OutputStream os = item.getOutputStream();
            IOUtils.copy(input, os);// 流转移
        } catch (IOException ioe) {
            log.error("getMultipartFile IOException", ioe);
        }
        return new CommonsMultipartFile(item);
    }

    /**
     * 读取文件内容
     */
    public static String readFileContent(MultipartFile file) {
        StringBuilder value = new StringBuilder("");
        // 读取文件内容到Stream流中,按行读取
        try (Scanner sc = new Scanner(file.getInputStream())) {
            while (sc.hasNextLine()) {  //按行读取字符串
                value.append(sc.nextLine().trim());
                value.append("\n");
            }
        } catch (IOException e) {
            log.error("readFileContent IOException:", e);
        }
        return value.toString();
    }

    /**
     * 通用文件上传
     *
     * @param file       需要上传的文件
     * @param uploadPath 上传到的路径
     */
    public static boolean uploadFile(MultipartFile file, String uploadPath) {
        File newFile = new File(uploadPath);
        if (!newFile.getParentFile().exists()) {
            newFile.getParentFile().mkdirs();
        }
        try {
            InputStream inputStream = file.getInputStream();
            OutputStream os = null;
            byte[] bs = new byte[1024];
            int len;
            os = new FileOutputStream(newFile);
            while ((len = inputStream.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
            os.close();
            inputStream.close();
        } catch (IOException ioe) {
            log.error("uploadFile IOException:", ioe);
        }
        return true;
    }

    /**
     * 通用文件下载
     *
     * @param filePath 需要下载的文件
     */
    public static void downloadFile(HttpServletResponse response, String filePath) {
        //根据文件路径获取文件
        File packetFile = new File(filePath);
        String fileName = packetFile.getName();
        File file = new File(filePath);
        if (file.exists()) {
            // 配置文件下载
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            // 下载文件能正常显示中文
            try {
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                log.error("downloadFile UnsupportedEncodingException", e);
            }
            // 实现文件下载
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
            } catch (IOException ioe) {
                log.error("downloadFile IOException:", ioe);
            }
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    log.error("关闭bis流异常:", e);
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    log.error("关闭fis流异常:", e);
                }
            }
        } else {
            log.info(filePath + ":文件下载失败,文件不存在!");
        }
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值