原理参考:
https://blog.csdn.net/Shuphen/article/details/123543812
Java后端实现:
//获取源文件大小
long fileSize = inputFile.length();
//文件字节流的起始位置,截止位置
int startRange=0,endRange=0;
boolean isRange = false;
int readSize =0 ;
//文件大于2M才进行分页加载
if(fileSize > 2*1024*1024){
String range = request.getHeader("range");
//状态码
int status = 200;
if(StringUtils.isBlank(range)){
//分页加载第一次请求,设置默认分页
range = "bytes=0-65535";
response.addHeader("Accept-Ranges","bytes");
//首次请求,直接返回支持分片加载即可
}else{
status =206;
}
range = range.split("=")[1];
String[] rangeArr = range.split("-");
startRange = NumberUtils.getInteger(rangeArr[0]);
endRange = NumberUtils.getInteger(rangeArr[1]);
if(startRange>endRange || endRange>fileSize){
return;
}
//需要读取的大小
readSize = endRange - startRange + 1;
isRange = true;
response.setStatus(status);
response.setContentLengthLong(status==200?fileSize : readSize);
response.addHeader("Content-Range","bytes "+startRange+"-"+endRange+"/"+fileSize);
response.addHeader("Access-Control-Expose-Headers","Accept-Ranges,Content-Range");
//分片的文件流
//response.setContentType("application/octet-stream");
}
OutputStream outputStream = null;
BufferedInputStream bufferedInputStream = null;
try {
outputStream = response.getOutputStream();
bufferedInputStream = new BufferedInputStream(new FileInputStream(inputFile));
if(isRange){
bufferedInputStream.skip(startRange);
}
int count = 0;
byte[] buffer = new byte[1024*1024];
while ((count = bufferedInputStream.read(buffer,0,buffer.length)) != -1) {
if(isRange){
if(readSize<=count){
outputStream.write(buffer,0,readSize);
break;
}else{
outputStream.write(buffer, 0, count);
readSize = readSize - count;
}
}else{
outputStream.write(buffer, 0, count);
}
}
outputStream.flush();
} catch (Exception e) {
log.error("预览PDF文档发送错误:"+e.getMessage());
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bufferedInputStream != null) {
try {
bufferedInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
PDF.js设置更改
找到viewer.js,搜索disableAutoFetch关键字,把false改成true即可实现按需加载