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

    }
相关推荐
yaoxin5211232 小时前
390. Java IO API - WatchDir 示例
java·前端·python
sunshine8852 小时前
财务RPA的深水区应用:超越自动化,迈向智能决策支持
数据库
efir OONA3 小时前
MySQL数据库误删恢复_mysql 数据 误删
数据库·mysql·adb
zhangchaoxies3 小时前
如何在 Go 中安全复制接口指针所指向的值
jvm·数据库·python
Halo_tjn3 小时前
Java 基于字符串相关知识点
java·开发语言·算法
梦想的颜色3 小时前
java 利用redis来限制用户频繁点击
java·开发语言
陈陈CHENCHEN3 小时前
【数据库】MySQL 8.0.40 至 8.0.44 RPM 方式升级指南
数据库·mysql
m0_734949794 小时前
怎么利用Navicat进行调整备份文件压缩等级_详细配置与操作步骤
jvm·数据库·python
T.i.s4 小时前
番外续2-MIT-BIH Arrhythmia Database
数据库
有味道的男人5 小时前
AI 效率翻倍:对接 1688 拍立淘接口,商品全量信息一键抓取
数据库