使用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);

    }
相关推荐
在荒野的梦想1 分钟前
LangChain4j 集成若依单体应用 | 5 大 AI 功能实战:多轮对话、流式输出、RAG 知识库
java·人工智能
hutengyi5 分钟前
保姆级JavaWeb项目创建、部署、连接数据库(tomcat)
数据库·tomcat·firefox
苏渡苇6 分钟前
ConcurrentHashMap.computeIfAbsent():高并发下安全初始化的终极方案
java·安全·jdk·高并发·hashmap·concurrent
FinelyYang9 分钟前
nginx的docker镜像封禁地区IP
java·nginx·docker
寰宇的行者11 分钟前
深入理解 Django 异步视图中的 `sync_to_async` 与协程
数据库·django
草莓熊Lotso13 分钟前
MySQL 索引特性与性能优化全解
android·运维·数据库·c++·mysql·性能优化
空空潍17 分钟前
Spring AI 实战系列(六):Tool Calling深度实战,让大模型自动调用你的业务接口
java·人工智能·spring
NoSi EFUL18 分钟前
Redis6.2.6下载和安装
java
薛定谔的悦18 分钟前
站控显示下级从控EMS的版本信息开发(设计多线程和TCP通讯)
linux·网络·数据库·网络协议·tcp/ip·ems
bcbobo21cn21 分钟前
C#使用一维数组作为参数传递
开发语言·数据库·c#·一维数组