原理参考:

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即可实现按需加载

GitHub 加速计划 / pd / pdf.js
47.48 K
9.86 K
下载
PDF Reader in JavaScript
最近提交(Master分支:3 个月前 )
18284815 [Editor] Update the disclaimer string in the new alt-text dialog (bug 1911738) 3 个月前
fc602c65 And tweak the css in order to take into account that disclaimer can be on two (or more lines). 3 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐