文件上传与下载的工具类封装

1.文件上传

     /*文件上传*/
    public static String uploadFile(MultipartFile file, String savePath) {
        FileOutputStream out = null;
        logger.info(savePath);
        try {
            File uploadPath = new File(savePath);
            if (!uploadPath.exists()||uploadPath.isDirectory()) {
                uploadPath.mkdirs();
            }
            /*转换成字节数组*/
            byte[] bytes = file.getBytes();
            /*获取原文件名*/
            String originalFilename = file.getOriginalFilename();
            /*构造新的文件名,避免同名文件覆盖*/
            String newFileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + "_" + new Random().nextInt(99999) + "_" + originalFilename;
            /*指定文件上传路径*/
            out = new FileOutputStream(uploadPath + "/" + newFileName);
            out.write(bytes);
            out.flush();
            logger.info("文件上传成功");
            return savePath+"/"+newFileName;
        } catch (Exception e) {
            logger.error("文件上传失败 -->> ", e);
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (Exception e) {
                logger.error("uploadFile error -->> ", e);
            }
        }
        return null;


    }

2.文件下载

    /*文件下载:以流的方式*/
    public static ResponseEntity downloadFile(String path, HttpServletResponse response) {
        logger.info("传入路径参数" + path);
        //设置文件路径
        File file = new File(path);
        //获取文件名
        String fileName = file.getName();
        logger.info("文件名" + file.getName());

        response.setContentType("application/octet-stream");//告诉浏览器输出内容为流
        response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
        response.addHeader("Content-Length", "" + file.length());
        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);
            }
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        logger.info("下载成功");
        return null;
    }

3.fileUtil类完整代码

package com.bairuitech.anychat.file.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

public class FileUtil {
    private static final Logger logger = LoggerFactory.getLogger(FileUtil.class);

    /*文件上传*/
    public static String uploadFile(MultipartFile file, String savePath) {
        FileOutputStream out = null;
        logger.info(savePath);
        try {
            File uploadPath = new File(savePath);
            if (!uploadPath.exists()||uploadPath.isDirectory()) {
                uploadPath.mkdirs();
            }
            /*转换成字节数组*/
            byte[] bytes = file.getBytes();
            /*获取原文件名*/
            String originalFilename = file.getOriginalFilename();
            /*构造新的文件名,避免同名文件覆盖*/
            String newFileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + "_" + new Random().nextInt(99999) + "_" + originalFilename;
            /*指定文件上传路径*/
            out = new FileOutputStream(uploadPath + "/" + newFileName);
            out.write(bytes);
            out.flush();
            logger.info("文件上传成功");
            return savePath+"/"+newFileName;
        } catch (Exception e) {
            logger.error("文件上传失败 -->> ", e);
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (Exception e) {
                logger.error("uploadFile error -->> ", e);
            }
        }
        return null;


    }

    /*文件下载:以流的方式*/
    public static ResponseEntity downloadFile(String path, HttpServletResponse response) {
        logger.info("传入路径参数" + path);
        //设置文件路径
        File file = new File(path);
        //获取文件名
        String fileName = file.getName();
        logger.info("文件名" + file.getName());

        response.setContentType("application/octet-stream");//告诉浏览器输出内容为流
        response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
        response.addHeader("Content-Length", "" + file.length());
        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);
            }
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        logger.info("下载成功");
        return null;
    }

}

4.控制层

//springboot上传文件出现异常java.lang.IllegalArgumentException: Expected MultipartHttpServletRequest: is a MultipartResolver configured 加上这一段可以解决问题
  @Bean
    public CommonsMultipartResolver multipartResolver() {
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
        multipartResolver.setDefaultEncoding("UTF-8");
        multipartResolver.setMaxUploadSize(104857600);
        return multipartResolver;
    }

    //文件上传
    @RequestMapping("/upload")
    public FileResult upload(MultipartFile file) {
        String fileUrl = FileUtil.uploadFile(file, savePath);
        return FileResult.success(fileUrl);
    }

    //文件下载
    @RequestMapping("/download")
    public FileResult download(HttpServletResponse response, String path) {
        ResponseEntity responseEntity = FileUtil.downloadFile(path, response);
        return FileResult.success("文件下载成功", responseEntity);
    }

5.postMan测试文件上传成功
在这里插入图片描述
6.浏览器访问下载接口
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值