栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot项目NIO下载文件初体验

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot项目NIO下载文件初体验

 NIO相关概念:

缓冲区(buffer) 通道(channel) 选择器(selector)

import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;


@RestController
@Slf4j
@Api(tags = {"下载文件nio" })
public class NioFileTransmitController {

    @GetMapping("/nio/download")
    public void downloadExcelTemplate(HttpServletRequest request, HttpServletResponse response) {
        String fileName = "1-5 网站前台 活动与招聘.zip";
        //下面是源文件的路径,也可以自己定义,例如:"E:BaiduNetdiskDownload1-5 网站前台 活动与招聘.zip       
        String filePath ="E:\BaiduNetdiskDownload\1-5 网站前台 活动与招聘.zip";
        log.info("导入模板路径" + filePath);

        FileInputStream fin = null;
        FileChannel channel = null;
        try {
            request.setCharacterEncoding("UTF-8");
            File file = new File(filePath);
            long fileLength = file.length();
            log.warn("文件大小: {}MB", fileLength/1024/1024);
            fin = new FileInputStream(file);
            //对中文名进行编码,解决中文乱码
            String encodedFileName = URLEncoder.encode(fileName, "UTF-8");
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            //指定文件下载,并解决中文名乱码
            response.setHeader("Content-Disposition", "attachment;filename*=utf-8'zh_cn'" + encodedFileName);//重点
            response.setHeader("Content-Length", String.valueOf(fileLength));
            response.setContentType("application/octet-stream");
            response.setContentType("application/force-download");

            channel = fin.getChannel();

            int buffSize = 1024;
            ByteBuffer buffer = ByteBuffer.allocate(4096);
            byte[] byteArr = new byte[buffSize];
            int nGet = 0;
            while (channel.read(buffer) != -1) {
                buffer.flip();
                while (buffer.hasRemaining()) {
                    nGet = Math.min(buffer.remaining(), buffSize);
                    // read bytes from disk
                    buffer.get(byteArr, 0, nGet);
                    // write bytes to output
                    response.getOutputStream().write(byteArr);
                }
                buffer.clear();
            }
        } catch (Exception e) {
            log.error("下载Excel模板失败");
            e.printStackTrace();
        } finally {
            if (channel != null && fin != null) {
                try {
                    channel.close();
                    fin.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            log.info("下载流程走完!");
        }
    }
}

在本地浏览器直接访问http://ip:port/nio/download即可下载文件

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/866103.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号