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;
/**
* @Description:
* @Author Be.insighted
* @Date 2022/5/7 11:27
*/
@RestController
@Slf4j
@Api(tags = {"下载文件nio" })
public class NioFileTransmitController {
@GetMapping("/nio/download")
public void downloadExcelTemplate(HttpServletRequest request, HttpServletResponse response) {
String fileName = "1-5 网站前台 活动与招聘.zip";
//下面是源文件的路径,也可以自己定义,例如:"E:\BaiduNetdiskDownload\1-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即可下载文件