使用nio代替传统流实现文件上传和下载功能

1.文件下载

java 复制代码
/**NIO文件下载工具类
 * @author olalu
 */
public class NioDownloadUtils {

    /**
     * @description:
     * @param file: 要下在文件
     * @return: void
     */
    public static void downloadDoc(File file,HttpServletResponse response) throws IOException {
        OutputStream outputStream = response.getOutputStream();
        String contentType = Files.probeContentType(Paths.get(file.getAbsolutePath()));
        //设置响应头
        response.setHeader("Content-Type", contentType);
        response.setHeader("Content-Disposition", "attachment;filename="+ new String(file.getName().getBytes("utf-8"),"ISO8859-1"));
        response.setContentLength((int) file.length());
        //获取文件输入流
        FileInputStream fileInputStream = new FileInputStream(file);
        //获取输出流通道
        WritableByteChannel writableByteChannel = Channels.newChannel(outputStream);
        FileChannel fileChannel = fileInputStream.getChannel();
        //采用零拷贝的方式实现文件的下载
        fileChannel.transferTo(0,fileChannel.size(),writableByteChannel);
        //关闭对应的资源
        fileChannel.close();
        outputStream.flush();
        writableByteChannel.close();
    }

    public static void downloadDoc(String path,HttpServletResponse response) throws IOException {
        File file = new File(path);
        if (!file.exists()){
            throw new RuntimeException("文件不存在");
        }
        downloadDoc(file,response);
    }

}

2.文件上传

java 复制代码
/**
     * 文件上传方法
     */
    public static Result uploading(MultipartFile file) {
        //获取文件名
        String realName = file.getOriginalFilename();
        String newName = null;
        if(realName != null && realName != ""){
            //获取文件后缀
            String suffixName = realName.substring(realName.lastIndexOf("."));
            //生成新名字
            newName = UUID.randomUUID().toString().replaceAll("-", "")+suffixName;
        }else {
            return Result.fail("文件名不可为空");
        }
        //创建流
        FileInputStream fis = null;
        FileOutputStream fos = null;
        //创建通道
        FileChannel inChannel = null;
        FileChannel outChannel = null;
        try {
            fis = (FileInputStream)file.getInputStream();
            //开始上传
            fos = new FileOutputStream(UPLOAD_URL+"\\"+newName);
            //通道间传输
            inChannel = fis.getChannel();
            outChannel = fos.getChannel();
            //上传
            inChannel.transferTo(0,inChannel.size(),outChannel);

        }catch (IOException e){
            return Result.fail("文件上传路径错误");
        }finally {
            //关闭资源
            try {
                if (fis != null) {
                    fis.close();
                }
                if (fos != null) {
                    fos.close();
                }
                if (inChannel != null) {
                    inChannel.close();
                }
                if (outChannel != null) {
                    outChannel.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return Result.ok(newName);

    }
相关推荐
2301_782659181 分钟前
C#怎么使用LINQ Contains包含判断 C#如何用Contains实现类似SQL IN查询的集合包含判断【语法】
jvm·数据库·python
程序猿乐锅3 分钟前
Java第十三篇:Stream流
java·笔记
2301_773553625 分钟前
如何优化深分页场景下的回表代价_延迟关联与主键游标分页
jvm·数据库·python
林三的日常5 分钟前
SpringBoot + Druid SQL Parser 解析表名、字段名(纯Java,最佳方案)
java·spring boot·sql
志栋智能9 分钟前
从“成本中心”到“效率引擎”:超自动化巡检的转型之路
运维·数据库·自动化
deviant-ART10 分钟前
java stream 的 findFirst 和 findAny 踩坑点
java·开发语言·后端
weixin_5689960615 分钟前
Golang怎么实现跳表数据结构_Golang如何用Skip List实现有序数据的快速查找【方法】
jvm·数据库·python
蜜獾云16 分钟前
交易系统之数据库弱依赖解决方案
数据库·oracle
青衫码上行17 分钟前
【从零开始学习JVM】字符串常量池
java·jvm·学习·面试·string
卢傢蕊20 分钟前
NoSQL 之Redis 集群
数据库·redis·nosql