制作网站价格不一/青岛网站seo分析
一、简介
随着互联网的快速发展,大文件的传输成为了互联网应用的重要组成部分。然而,由于网络不稳定等因素的影响,大文件的传输经常会出现中断的情况,这时需要重新传输,导致传输效率低下。
为了解决这个问题,可以实现大文件的断点续传功能。断点续传功能可以在传输中断后继续传输,而不需要从头开始传输。这样可以大大提高传输的效率。
Spring Boot是一个快速开发的Java Web开发框架,可以帮助我们快速搭建一个Web应用程序。在Spring Boot中,我们可以很容易地实现大文件的断点续传功能。
本文将介绍如何使用Spring Boot实现大文件的断点续传功能。
二、Spring Boot实现大文件断点续传的原理
实现大文件的断点续传功能,需要在客户端和服务端都进行相应的实现。
实现示例1
服务端如何将一个大视频文件做切分,分段响应给客户端,让浏览器可以渐进式地播放。
Spring Boot实现HTTP分片下载断点续传,从而实现H5页面的大视频播放问题,实现渐进式播放,每次只播放需要播放的内容就可以了,不需要加载整个文件到内存中。
文件的断点续传、文件多线程并发下载(迅雷就是这么玩的)等。
<dependencyManagement><dependencies><dependency><groupId>cn.hutool</groupId><artifactId>hutool-bom</artifactId><version>5.8.18</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement><dependencies><dependency><groupId>cn.hutool</groupId><artifactId>hutool-core</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency></dependencies>
代码实现
ResourceController
package com.example.insurance.controller;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;import com.example.insurance.common.ContentRange;
import com.example.insurance.common.MediaContentUtil;
import com.example.insurance.common.NioUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRange;
import org.springframework.http.HttpStatus;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;/*** 内容资源控制器*/
@SuppressWarnings("unused")
@Slf4j
@RestController("resourceController")
@RequestMapping(path = "/resource")
public class ResourceController {/*** 获取文件内容** @param fileName 内容文件名称* @param response 响应对象*/@GetMapping("/media/{fileName}")public void getMedia(@PathVariable String fileName, HttpServletRequest request, HttpServletResponse response,@RequestHeader HttpHeaders headers) {
// printRequestInfo(fileName, request, headers);String filePath = MediaContentUtil.filePath();try {this.download(fileName, filePath, request, response, headers);} catch (Exception e) {log.error("getMedia error, fileName={}", fileName, e);}}/*** 获取封面内容** @param fileName 内容封面名称* @param response 响应对象*/@GetMapping("/cover/{fileName}")public void getCover(@PathVariable String fileName, HttpServletRequest request, HttpServletResponse response,@RequestHeader HttpHeaders headers) {
// printRequestInfo(fileName, request, headers);String filePath = MediaContentUtil.filePath();try {this.download(fileName, filePath, request, response, headers);} catch (Exception e) {log.error("getCover error, fileName={}", fileName, e);}}// ======= internal =======private static void printRequestInfo(String fileName, HttpServletRequest request, HttpHeaders headers) {String requestUri = request.getRequestURI();String queryString = request.getQueryString();log.debug("file={}, url={}?{}", fileName, requestUri, queryString);log.info("headers={}", headers);}/*** 设置请求响应状态、头信息、内容类型与长度 等。* <pre>* <a href="https://www.rfc-editor.org/rfc/rfc7233">* HTTP/1.1 Range Requests</a>* 2. Range Units* 4. Responses to a Range Request** <a href="https://www.rfc-editor.org/rfc/rfc2616.html">* HTTP/1.1</a>* 10.2.7 206 Partial Content* 14.5 Accept-Ranges* 14.13 Content-Length* 14.16 Content-Range* 14.17 Content-Type* 19.5.1 Content-Disposition* 15.5 Content-Disposition Issues** <a href="https://www.rfc-editor.org/rfc/rfc2183">* Content-Disposition</a>* 2. The Content-Disposition Header Field* 2.1 The Inline Disposition Type* 2.3 The Filename Parameter* </pre>** @param response 请求响应对象* @param fileName 请求的文件名称* @param contentType 内容类型* @param contentRange 内容范围对象*/private static void setResponse(HttpServletResponse response, String fileName, String contentType,ContentRange contentRange) {// http状态码要为206:表示获取部分内容response.setStatus(HttpStatus.PARTIAL_CONTENT.value());// 支持断点续传,获取部分字节内容// Accept-Ranges:bytes,表示支持Range请求response.setHeader(HttpHeaders.ACCEPT_RANGES, ContentRange.BYTES_STRING);// inline表示浏览器直接使用,attachment表示下载,fileName表示下载的文件名response.setHeader(HttpHeaders.CONTENT_DISPOSITION,"inline;filename=" + MediaContentUtil.encode(fileName));// Content-Range,格式为:[要下载的开始位置]-[结束位置]/[文件总大小]// Content-Range: bytes 0-10/3103,格式为bytes 开始-结束/全部response.setHeader(HttpHeaders.CONTENT_RANGE, contentRange.toContentRange());response.setContentType(contentType);// Content-Length: 11,本次内容的大小response.setContentLengthLong(contentRange.applyAsContentLength());}/*** <a href="https://www.jianshu.com/p/08db5ba3bc95">* Spring Boot 处理 HTTP Headers</a>*/private void download(String fileName, String path, HttpServletRequest request, HttpServletResponse response,HttpHeaders headers)throws IOException {Path filePath = Paths.get(path + fileName);if (!Files.exists(filePath)) {log.warn("file not exist, filePath={}", filePath);return;}long fileLength = Files.size(filePath);
// long fileLength2 = filePath.toFile().length() - 1;
// // fileLength=1184856, fileLength2=1184855
// log.info("fileLength={}, fileLength2={}", fileLength, fileLength2);// 内容范围ContentRange contentRange = applyAsContentRange(headers, fileLength, request);// 要下载的长度long contentLength = contentRange.applyAsContentLength();log.debug("contentRange={}, contentLength={}", contentRange, contentLength);// 文件类型String contentType = request.getServletContext().getMimeType(fileName);// mimeType=video/mp4, CONTENT_TYPE=nulllog.debug("mimeType={}, CONTENT_TYPE={}", contentType, request.getContentType());setResponse(response, fileName, contentType, contentRange);// 耗时指标统计StopWatch stopWatch = new StopWatch("downloadFile");stopWatch.start(fileName);try {// case-1.参考网上他人的实现
// if (fileLength >= Integer.MAX_VALUE) {
// NioUtils.copy(filePath, response, contentRange);
// } else {
// NioUtils.copyByChannelAndBuffer(filePath, response, contentRange);
// }// case-2.使用现成APINioUtils.copyByBio(filePath, response, contentRange);
// NioUtils.copyByNio(filePath, response, contentRange);// case-3.视频分段渐进式播放
// if (contentType.startsWith("video")) {
// NioUtils.copyForBufferSize(filePath, response, contentRange);
// } else {
// // 图片、PDF等文件
// NioUtils.copyByBio(filePath, response, contentRange);
// }} finally {stopWatch.stop();log.info("download file, fileName={}, time={} ms", fileName, stopWatch.getTotalTimeMillis());}}private static ContentRange applyAsContentRange(HttpHeaders headers, long fileLength, HttpServletRequest request) {/** 3.1. Range - HTTP/1.1 Range Requests* https://www.rfc-editor.org/rfc/rfc7233#section-3.1* Range: "bytes" "=" first-byte-pos "-" [ last-byte-pos ]** For example:* bytes=0-* bytes=0-499*/// Range:告知服务端,客户端下载该文件想要从指定的位置开始下载List<HttpRange> httpRanges = headers.getRange();String range = request.getHeader(HttpHeaders.RANGE);// httpRanges=[], range=null// httpRanges=[448135688-], range=bytes=448135688-log.debug("httpRanges={}, range={}", httpRanges, range);// 开始下载位置long firstBytePos;// 结束下载位置long lastBytePos;if (CollectionUtils.isEmpty(httpRanges)) {firstBytePos = 0;lastBytePos = fileLength - 1;} else {HttpRange httpRange = httpRanges.get(0);firstBytePos = httpRange.getRangeStart(fileLength);lastBytePos = httpRange.getRangeEnd(fileLength);}return new ContentRange(firstBytePos, lastBytePos, fileLength);}
}
NioUtils
package com.example.insurance.common;import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.io.NioUtil;
import cn.hutool.core.io.StreamProgress;
import cn.hutool.core.io.unit.DataSize;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.connector.ClientAbortException;/*** NIO相关工具封装,主要针对Channel读写、拷贝等封装*/
@Slf4j
public final class NioUtils {/*** 缓冲区大小 16KB** @see NioUtil#DEFAULT_BUFFER_SIZE* @see NioUtil#DEFAULT_LARGE_BUFFER_SIZE*/
// private static final int BUFFER_SIZE = NioUtil.DEFAULT_MIDDLE_BUFFER_SIZE;private static final int BUFFER_SIZE = (int) DataSize.ofKilobytes(16L).toBytes();/*** <pre>* <a href="https://blog.csdn.net/qq_32099833/article/details/109703883">* Java后端实现视频分段渐进式播放</a>* 服务端如何将一个大的视频文件做切分,分段响应给客户端,让浏览器可以渐进式地播放。* 文件的断点续传、文件多线程并发下载(迅雷就是这么玩的)等。** <a href="https://blog.csdn.net/qq_32099833/article/details/109630499">* 大文件分片上传前后端实现</a>* </pre>*/public static void copyForBufferSize(Path filePath, HttpServletResponse response, ContentRange contentRange) {String fileName = filePath.getFileName().toString();RandomAccessFile randomAccessFile = null;OutputStream outputStream = null;try {// 随机读文件randomAccessFile = new RandomAccessFile(filePath.toFile(), "r");// 移动访问指针到指定位置randomAccessFile.seek(contentRange.getStart());// 注意:缓冲区大小 2MB,视频加载正常;1MB时有部分视频加载失败int bufferSize = BUFFER_SIZE;//获取响应的输出流outputStream = new BufferedOutputStream(response.getOutputStream(), bufferSize);// 每次请求只返回1MB的视频流byte[] buffer = new byte[bufferSize];int len = randomAccessFile.read(buffer);//设置此次相应返回的数据长度response.setContentLength(len);// 将这1MB的视频流响应给客户端outputStream.write(buffer, 0, len);log.info("file download complete, fileName={}, contentRange={}",fileName, contentRange.toContentRange());} catch (ClientAbortException | IORuntimeException e) {// 捕获此异常表示用户停止下载log.warn("client stop file download, fileName={}", fileName);} catch (Exception e) {log.error("file download error, fileName={}", fileName, e);} finally {IoUtil.close(outputStream);IoUtil.close(randomAccessFile);}}/*** 拷贝流,拷贝后关闭流。** @param filePath 源文件路径* @param response 请求响应* @param contentRange 内容范围*/public static void copyByBio(Path filePath, HttpServletResponse response, ContentRange contentRange) {String fileName = filePath.getFileName().toString();InputStream inputStream = null;OutputStream outputStream = null;try {RandomAccessFile randomAccessFile = new RandomAccessFile(filePath.toFile(), "r");randomAccessFile.seek(contentRange.getStart());inputStream = Channels.newInputStream(randomAccessFile.getChannel());outputStream = new BufferedOutputStream(response.getOutputStream(), BUFFER_SIZE);StreamProgress streamProgress = new StreamProgressImpl(fileName);long transmitted = IoUtil.copy(inputStream, outputStream, BUFFER_SIZE, streamProgress);log.info("file download complete, fileName={}, transmitted={}", fileName, transmitted);} catch (ClientAbortException | IORuntimeException e) {// 捕获此异常表示用户停止下载log.warn("client stop file download, fileName={}", fileName);} catch (Exception e) {log.error("file download error, fileName={}", fileName, e);} finally {IoUtil.close(outputStream);IoUtil.close(inputStream);}}/*** 拷贝流,拷贝后关闭流。* <pre>* <a href="https://www.cnblogs.com/czwbig/p/10035631.html">* Java NIO 学习笔记(一)----概述,Channel/Buffer</a>* </pre>** @param filePath 源文件路径* @param response 请求响应* @param contentRange 内容范围*/public static void copyByNio(Path filePath, HttpServletResponse response, ContentRange contentRange) {String fileName = filePath.getFileName().toString();InputStream inputStream = null;OutputStream outputStream = null;try {RandomAccessFile randomAccessFile = new RandomAccessFile(filePath.toFile(), "r");randomAccessFile.seek(contentRange.getStart());inputStream = Channels.newInputStream(randomAccessFile.getChannel());outputStream = new BufferedOutputStream(response.getOutputStream(), BUFFER_SIZE);StreamProgress streamProgress = new StreamProgressImpl(fileName);long transmitted = NioUtil.copyByNIO(inputStream, outputStream,BUFFER_SIZE, streamProgress);log.info("file download complete, fileName={}, transmitted={}", fileName, transmitted);} catch (ClientAbortException | IORuntimeException e) {// 捕获此异常表示用户停止下载log.warn("client stop file download, fileName={}", fileName);} catch (Exception e) {log.error("file download error, fileName={}", fileName, e);} finally {IoUtil.close(outputStream);IoUtil.close(inputStream);}}/*** <pre>* <a href="https://blog.csdn.net/lovequanquqn/article/details/104562945">* SpringBoot Java实现Http方式分片下载断点续传+实现H5大视频渐进式播放</a>* SpringBoot 实现Http分片下载断点续传,从而实现H5页面的大视频播放问题,实现渐进式播放,每次只播放需要播放的内容就可以了,不需要加载整个文件到内存中。* 二、Http分片下载断点续传实现* 四、缓存文件定时删除任务* </pre>*/public static void copy(Path filePath, HttpServletResponse response, ContentRange contentRange) {String fileName = filePath.getFileName().toString();// 要下载的长度long contentLength = contentRange.applyAsContentLength();BufferedOutputStream outputStream = null;RandomAccessFile randomAccessFile = null;// 已传送数据大小long transmitted = 0;try {randomAccessFile = new RandomAccessFile(filePath.toFile(), "r");randomAccessFile.seek(contentRange.getStart());outputStream = new BufferedOutputStream(response.getOutputStream(), BUFFER_SIZE);// 把数据读取到缓冲区中byte[] buffer = new byte[BUFFER_SIZE];int len = BUFFER_SIZE;//warning:判断是否到了最后不足4096(buffer的length)个byte这个逻辑((transmitted + len) <= contentLength)要放前面//不然会会先读取randomAccessFile,造成后面读取位置出错;while ((transmitted + len) <= contentLength && (len = randomAccessFile.read(buffer)) != -1) {outputStream.write(buffer, 0, len);transmitted += len;log.info("fileName={}, transmitted={}", fileName, transmitted);}//处理不足buffer.length部分if (transmitted < contentLength) {len = randomAccessFile.read(buffer, 0, (int) (contentLength - transmitted));outputStream.write(buffer, 0, len);transmitted += len;log.info("fileName={}, transmitted={}", fileName, transmitted);}log.info("file download complete, fileName={}, transmitted={}", fileName, transmitted);} catch (ClientAbortException e) {// 捕获此异常表示用户停止下载log.warn("client stop file download, fileName={}, transmitted={}", fileName, transmitted);} catch (Exception e) {log.error("file download error, fileName={}, transmitted={}", fileName, transmitted, e);} finally {IoUtil.close(outputStream);IoUtil.close(randomAccessFile);}}/*** 通过数据传输通道和缓冲区读取文件数据。* <pre>* 当文件长度超过{@link Integer#MAX_VALUE}时,* 使用{@link FileChannel#map(FileChannel.MapMode, long, long)}报如下异常。* java.lang.IllegalArgumentException: Size exceeds Integer.MAX_VALUE* at sun.nio.ch.FileChannelImpl.map(FileChannelImpl.java:863)* at com.example.insurance.controller.ResourceController.download(ResourceController.java:200)* </pre>** @param filePath 源文件路径* @param response 请求响应* @param contentRange 内容范围*/public static void copyByChannelAndBuffer(Path filePath, HttpServletResponse response, ContentRange contentRange) {String fileName = filePath.getFileName().toString();// 要下载的长度long contentLength = contentRange.applyAsContentLength();BufferedOutputStream outputStream = null;FileChannel inChannel = null;// 已传送数据大小long transmitted = 0;long firstBytePos = contentRange.getStart();long fileLength = contentRange.getLength();try {inChannel = FileChannel.open(filePath, StandardOpenOption.READ, StandardOpenOption.WRITE);// 建立直接缓冲区MappedByteBuffer inMap = inChannel.map(FileChannel.MapMode.READ_ONLY, firstBytePos, fileLength);outputStream = new BufferedOutputStream(response.getOutputStream(), BUFFER_SIZE);// 把数据读取到缓冲区中byte[] buffer = new byte[BUFFER_SIZE];int len = BUFFER_SIZE;// warning:判断是否到了最后不足4096(buffer的length)个byte这个逻辑((transmitted + len) <= contentLength)要放前面// 不然会会先读取file,造成后面读取位置出错while ((transmitted + len) <= contentLength) {inMap.get(buffer);outputStream.write(buffer, 0, len);transmitted += len;log.info("fileName={}, transmitted={}", fileName, transmitted);}// 处理不足buffer.length部分if (transmitted < contentLength) {len = (int) (contentLength - transmitted);buffer = new byte[len];inMap.get(buffer);outputStream.write(buffer, 0, len);transmitted += len;log.info("fileName={}, transmitted={}", fileName, transmitted);}log.info("file download complete, fileName={}, transmitted={}", fileName, transmitted);} catch (ClientAbortException e) {// 捕获此异常表示用户停止下载log.warn("client stop file download, fileName={}, transmitted={}", fileName, transmitted);} catch (Exception e) {log.error("file download error, fileName={}, transmitted={}", fileName, transmitted, e);} finally {IoUtil.close(outputStream);IoUtil.close(inChannel);}}}
ContentRange
package com.example.insurance.common;import lombok.AllArgsConstructor;
import lombok.Getter;/*** 内容范围对象* <pre>* <a href="https://www.rfc-editor.org/rfc/rfc7233#section-4.2">* 4.2. Content-Range - HTTP/1.1 Range Requests</a>* Content-Range: "bytes" first-byte-pos "-" last-byte-pos "/" complete-length** For example:* Content-Range: bytes 0-499/1234* </pre>** @see org.apache.catalina.servlets.DefaultServlet.Range*/
@Getter
@AllArgsConstructor
public class ContentRange {/*** 第一个字节的位置*/private final long start;/*** 最后一个字节的位置*/private long end;/*** 内容完整的长度/总长度*/private final long length;public static final String BYTES_STRING = "bytes";/*** 组装内容范围的响应头。* <pre>* <a href="https://www.rfc-editor.org/rfc/rfc7233#section-4.2">* 4.2. Content-Range - HTTP/1.1 Range Requests</a>* Content-Range: "bytes" first-byte-pos "-" last-byte-pos "/" complete-length** For example:* Content-Range: bytes 0-499/1234* </pre>** @return 内容范围的响应头*/public String toContentRange() {return BYTES_STRING + ' ' + start + '-' + end + '/' + length;
// return "bytes " + start + "-" + end + "/" + length;}/*** 计算内容完整的长度/总长度。** @return 内容完整的长度/总长度*/public long applyAsContentLength() {return end - start + 1;}/*** Validate range.** @return true if the range is valid, otherwise false*/public boolean validate() {if (end >= length) {end = length - 1;}return (start >= 0) && (end >= 0) && (start <= end) && (length > 0);}@Overridepublic String toString() {return "firstBytePos=" + start +", lastBytePos=" + end +", fileLength=" + length;}
}
StreamProgressImpl
package com.example.insurance.common;import cn.hutool.core.io.StreamProgress;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;/*** 数据流进度条*/
@Slf4j
@AllArgsConstructor
public class StreamProgressImpl implements StreamProgress {private final String fileName;@Overridepublic void start() {log.info("start progress {}", fileName);}@Overridepublic void progress(long total, long progressSize) {log.debug("progress {}, total={}, progressSize={}", fileName, total, progressSize);}@Overridepublic void finish() {log.info("finish progress {}", fileName);}
}
MediaContentUtil
package com.example.insurance.common;import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;/*** 文件内容辅助方法集*/
public final class MediaContentUtil {public static String filePath() {String osName = System.getProperty("os.name");String filePath = "/data/files/";if (osName.startsWith("Windows")) {filePath = "D:\" + filePath;}
// else if (osName.startsWith("Linux")) {
// filePath = MediaContentConstant.FILE_PATH;
// }else if (osName.startsWith("Mac") || osName.startsWith("Linux")) {filePath = "/home/admin" + filePath;}return filePath;}public static String encode(String fileName) {return URLEncoder.encode(fileName, StandardCharsets.UTF_8);}public static String decode(String fileName) {return URLDecoder.decode(fileName, StandardCharsets.UTF_8);}
}
实现示例2
代码实现
(1)客户端需要实现以下功能:
- 建立连接:客户端需要连接服务端,并建立连接。
- 分块传输文件:客户端需要将文件分成若干块,并逐块传输。在传输中,每个块传输完成后,需要将已传输的位置发送给服务端,以便服务端记录传输位置。
- 计算MD5值:在传输完成后,客户端需要计算文件的MD5值,以确保传输的完整性。
- 与服务端比较MD5值:在计算出MD5值后,客户端需要将MD5值发送给服务端,并与服务端返回的MD5值比较,以确保传输的完整性。
(2)服务端需要实现以下功能:
- 建立连接:服务端需要等待客户端连接,并建立连接。
- 接收文件:服务端需要接收客户端传输的文件。在接收文件时,需要记录传输的位置,并在传输中断后继续接收文件。
- 计算MD5值:在接收完成后,服务端需要计算文件的MD5值,以确保传输的完整性。
- 返回MD5值:在计算出MD5值后,服务端需要将MD5值返回给客户端。
1.编写客户端代码
在客户端中,我们需要实现以下功能:
- 建立连接:使用Java的Socket类建立与服务端的连接。
- 分块传输文件:将文件分成若干块,并逐块传输。在传输中,每个块传输完成后,需要将已传输的位置发送给服务端,以便服务端记录传输位置。
- 计算MD5值:在传输完成后,计算文件的MD5值,以确保传输的完整性。
- 与服务端比较MD5值:将MD5值发送给服务端,并与服务端返回的MD5值比较,以确保传输的完整性。
以下是客户端代码的实现:
@RestController
@RequestMapping("/file")
public class FileController {@PostMapping("/upload")public ResponseEntity<?> uploadFile(@RequestParam("file") MultipartFile file,@RequestParam("fileName") String fileName,@RequestParam("startPosition") long startPosition) {try { // 建立连接Socket socket = new Socket("localhost", 8080);OutputStream outputStream = socket.getOutputStream();ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);// 分块传输文件FileInputStream fileInputStream = (FileInputStream) file.getInputStream();fileInputStream.skip(startPosition);byte[] buffer = new byte[1024];int len;while ((len = fileInputStream.read(buffer)) != -1) {outputStream.write(buffer, 0, len);}// 计算MD5值fileInputStream.getChannel().position(0);String md5 = DigestUtils.md5Hex(fileInputStream);// 与服务端比较MD5值InputStream inputStream = socket.getInputStream();ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);String serverMd5 = (String) objectInputStream.readObject();if (!md5.equals(serverMd5)) {throw new RuntimeException("MD5值不匹配");}// 关闭连接objectOutputStream.close();outputStream.close();socket.close();} catch (Exception e) {e.printStackTrace();return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());}return ResponseEntity.ok().build();}
}
2.编写服务端代码
在服务端中,我们需要实现以下功能:
- 建立连接:使用Java的ServerSocket类等待客户端连接,并建立连接。
- 接收文件:接收客户端传输的文件。在接收文件时,需要记录传输的位置,并在传输中断后继续接收文件。
- 计算MD5值:在接收完成后,计算文件的MD5值,以确保传输的完整性。
- 返回MD5值:将MD5值返回给客户端。
以下是服务端代码的实现:
@RestController
@RequestMapping("/file")
public class FileController {private final String FILE_PATH = "/tmp/upload/";@PostMapping("/upload")public ResponseEntity<?> uploadFile(HttpServletRequest request, @RequestParam("fileName") String fileName) {try {// 建立连接 ServerSocket serverSocket = new ServerSocket(8080);Socket socket = serverSocket.accept();InputStream inputStream = socket.getInputStream();ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);// 接收文件 String filePath = FILE_PATH + fileName;RandomAccessFile randomAccessFile = new RandomAccessFile(filePath, "rw");long startPosition = randomAccessFile.length();randomAccessFile.seek(startPosition);byte[] buffer = new byte[1024];int len;while ((len = inputStream.read(buffer)) != -1) {randomAccessFile.write(buffer, 0, len);} // 计算MD5值 FileInputStream fileInputStream = new FileInputStream(filePath);String md5 = DigestUtils.md5Hex(fileInputStream);// 返回MD5值 OutputStream outputStream = socket.getOutputStream();ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);objectOutputStream.writeObject(md5); // 关闭连objectInputStream.close();inputStream.close();randomAccessFile.close();socket.close();serverSocket.close();} catch (Exception e) {e.printStackTrace();return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());}return ResponseEntity.ok().build();}
}
3. 编写前端代码
在前端中,我们需要实现以下功能:
- 选择文件:提供一个文件选择框,让用户选择要上传的文件。
- 分块上传:将文件分块上传到服务器。在上传过程中,需要记录上传的位置,并在上传中断后继续上传。
以下是前端代码的实现:
<html>
<head><meta charset="UTF-8"><title>Spring Boot File Upload</title><script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
</head>
<body><input type="file" id="file">
<button onclick="upload()">Upload</button>
<script> var file;
var startPosition = 0;
$('#file').on('change', function () {file = this.files[0];
});function upload() {if (!file) {alert('Please select a file!');return;}var formData = new FormData();formData.append('file', file);formData.append('fileName', file.name);formData.append('startPosition', startPosition);$.ajax({url: '/file/upload',type: 'post',data: formData,cache: false,processData: false,contentType: false,success: function () {alert('Upload completed!');},error: function (xhr) {alert(xhr.responseText);},xhr: function () {var xhr = $.ajaxSettings.xhr();xhr.upload.onprogress = function (e) {if (e.lengthComputable) {var percent = e.loaded / e.total * 100;console.log('Upload percent: ' + percent.toFixed(2) + '%');}};return xhr;}});
}</script>
</body>
</html>
总结
本文介绍了如何使用Spring Boot实现大文件断点续传。在实现中,我们使用了Java的RandomAccessFile类来实现文件的分块上传和断点续传,使用了Spring Boot的RestController注解来实现Web服务的开发,使用了jQuery的Ajax函数来实现前端页面的开发。
在实际开发中,需要注意以下几点:
- 上传文件的大小和分块的大小需要根据实际情况进行设置,以确保上传速度和服务器的稳定性。
- 在上传过程中,需要对异常情况进行处理,以确保程序的健壮性。
- 在上传完成后,需要对上传的文件进行校验,以确保传输的完整性。
相关文章:

使用Spring Boot实现大文件断点续传及文件校验
一、简介 随着互联网的快速发展,大文件的传输成为了互联网应用的重要组成部分。然而,由于网络不稳定等因素的影响,大文件的传输经常会出现中断的情况,这时需要重新传输,导致传输效率低下。 为了解决这个问题ÿ…...

读取PDF中指定数据写入EXCEL文件
使用Java读取文件夹中的PDF文件,再读取文件中的指定的字体内容,然后将内容写入到Excel文件中,其中包含一些正则判断,可以忽略,字体以Corbel字体为例。 所需要的maven依赖为: <dependency><groupId>com.alibaba</groupId><artifactId>easyexcel…...

[黑马程序员SpringBoot2]——开发实用篇1
目录: 手工启动热部署自动启动热部署热部署范围配置关闭热部署功能第三方bean属性绑定松散绑定常用计量单位应用bean属性校验进制数据转换规则加载测试专用属性加载测试专用配置测试类中启动web环境发送虚拟请求匹配响应执行状态匹配响应体匹配响应体(json)匹配响应…...

Python------列表 集合 字典 推导式(本文以 集合为主)
推导式: 推导式comprehensions(又称解析式),是Python的一种独有特性。推导式是可以从一个数据序列 构建 另一个 新的数据序列(一个有规律的列表或控制一个有规律列表)的结构体。 共有三种推导ÿ…...

网工内推 | Linux运维,六险二金,最高30K,IE认证优先
01 上海域起 招聘岗位:Linux运维工程师 职责描述: 1.负责游戏产品运维相关的工作,流程文档、技术文档、功能脚本的编写整理 2.负责分析并排除系统、数据库、网络、应用等游戏产品运维中出现的故障及错误 3.负责对游戏产品项目进行线上部署、…...

服务器集群配置LDAP统一认证高可用集群(配置tsl安全链接)-centos9stream-openldap2.6.2
写在前面 因之前集群为centos6,已经很久没升级了,所以这次配置统一用户认证也是伴随系统升级到centos9时一起做的配套升级。新版的openldap配置大致与老版本比较相似,但有些地方配置还是有变化,另外,铺天盖地的帮助文…...

12-1- GAN -简单网络-线性网络
功能 随机噪声→生成器→MINIST图像。 训练方法 0 损失函数:gan的优化目标是一个对抗损失,是二分类问题,用BCELoss 1 判别器的训练,首先固定生成器参数不变,其次判别器应当将真实图像判别为1,生成图像判别为0 loss=loss(real_out, 1)+loss(fake_out, 0) 2 生成器的…...

Antv/G2 分组柱状图+折线图双轴图表
<!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><meta name"viewport" content"widthdevice-width,heightdevice-height"><title>分组柱状图折线图双轴图表</title><styl…...

springboot323基于Java的美妆购物网站的设计与实现
交流学习: 更多项目: 全网最全的Java成品项目列表 https://docs.qq.com/doc/DUXdsVlhIdVlsemdX 演示 项目功能演示: ————————————————...

vue项目本地开发完成后部署到服务器后报404
vue项目本地开发完成后部署到服务器后报404是什么原因呢? 一、如何部署 前后端分离开发模式下,前后端是独立布署的,前端只需要将最后的构建物上传至目标服务器的web容器指定的静态目录下即可 我们知道vue项目在构建后,是生成一系…...

Android设计模式--状态模式
真知即所以为行,不行不足谓之知 一,定义 当一个对象的内在状态改变时,允许改变其行为,这个对象看起来像是改变了其类。 这么说可能很难理解,通俗来讲就是当一个对象它有多种状态的时候,把每一种状态的行为…...

C++关系运算符重载
#include<iostream> using namespace std;class Person { public:string name;int age;Person(string n, int a){name n;age a;}//friend bool operator(Person& p1, Person& p2); 使用友元//成员函数实现函数关系符重载bool operator(Person& p) {if (na…...

HLS基础issue
hls 是一个用C/c 来开发PL ,产生rtl的工具 hls是按照rtl code来运行的 , 但是rtl会在不同器件调用不同的源语; 可能产生的ip使用在vivado另外一个器件的话 会存在问题; Hls : vivado ip , vitis kernel 是…...

C#特性(Attribute)
C#特性(Attribute)是一种在程序中添加元数据的机制,它可以为代码提供额外的信息和指示。通过使用特性,我们可以为类、方法、属性等元素添加标记,以便在运行时进行更多的操作和决策。 C#特性是一种声明式编程的工具&…...

【设计模式】七大设计原则
七大设计原则 文章目录 七大设计原则一、概述二、单一职责原则三、接口隔离原则四、依赖倒转原则五、里氏替换原则六、开闭原则七、迪米特法则八、合成复用原则 一、概述 设计模式是为了让程序(软件),具有更好代码重用性,可读性,可扩展性&am…...

思维导图软件 Xmind mac中文版特点介绍
XMind 2022 mac是一款思维导图软件,可以帮助用户创建各种类型的思维导图和概念图。 XMind mac软件特点 - 多样化的导图类型:XMind提供了多种类型的导图,如鱼骨图、树形图、机构图等,可以满足不同用户的需求。 - 强大的功能和工具&…...

Day32力扣打卡
打卡记录 买卖股票的最佳时机 IV(状态机DP) 链接 class Solution:def maxProfit(self, k: int, prices: List[int]) -> int:n len(prices)max lambda x, y: x if x > y else yf [[-0x3f3f3f3f] * 2 for _ in range(k 2)]for i in range(k 2…...

抗击.Elbie勒索病毒:如何应对.Elbie病毒威胁,保卫您的数据
导言: .Elbie勒索病毒如今成为网络世界中的一大威胁,其狡猾性让用户防不胜防。本文将深入介绍.Elbie病毒的特点、对数据的威胁,提供被感染文件的恢复方法,并详述一系列强化网络安全的预防措施,让您远离.Elbie勒索病毒…...

Vue3 函数式弹窗
运行环境 vue3vitetselement-plus 开发与测试 1. 使用h、render函数创建Dialog 建议可在plugins目录下创建dialog文件夹,创建index.ts文件,代码如下 import { h, render } from "vue";/*** 函数式弹窗* param component 组件* param opti…...

如何解决 Critical dependency: the request of a dependency is an expression ?
更多ruoyi-nbcio功能请看演示系统 gitee源代码地址 前后端代码: ruoyi-nbcio: nbcio-boot的若依版本,基于ruoyi-flowable-plus和flowable6.7.2,目前处于开发功能完善阶段,目标是打造一个最好的若依平台上flowable流程管理系统开源版本&…...

挑战视觉边界,探索图形验证码背后的黑科技
在日常生活中,我们登录网站或者其他平台时,在填写完账号密码之后,还会让我们填写4或6位的数字或者英文字母等,填写正确才能请求登录。这个其实是防止某一个特定注册用户用特定程序暴力破解方式进行不断的登陆尝试,如下…...

【网络奇缘】- 计算机网络|网络类型|性能指标
🌈个人主页: Aileen_0v0🔥系列专栏: 一见倾心,再见倾城 --- 计算机网络~💫个人格言:"没有罗马,那就自己创造罗马~" 目录 计算机网络分类 1.根据范围分类 编辑 2.按使用者分编辑 3.按交换技术分 编辑4.按拓扑结构分 …...

Leetcode—剑指Offer LCR 140.训练计划II【简单】
2023每日刷题(三十三) Leetcode—LCR 140.训练计划II 实现代码 /*** Definition for singly-linked list.* struct ListNode {* int val;* struct ListNode *next;* };*/ struct ListNode* trainingPlan(struct ListNode* head, int cnt) {str…...

梦想编织者——Adobe Dreamweaver
今天,我们来谈谈一款在Adobe系列中推出的一款Adobe Dreamweaver,简称“DW”,中文名称 “梦想编织者”,是集网页制作和管理网站于一身的所见即所得网页代码编辑器。 利用对 HTML、CSS、JavaScript等内容的支持,设计人员…...

springMVC学习笔记-请求映射,参数绑定,响应,restful,响应状态码,springMVC拦截器
目录 概述 springMVC做了什么 springMVC与struts2区别 springMVC整个流程是一个单向闭环 springMVC具体的处理流程 springMVC的组成部分 请求映射 RequestMapping 用法 属性 1.value 2.method GET方式和POST方式 概述 HTTP给GET和POST做了哪些规定 GET方式&…...

Python实现视频字幕时间轴格式转换
自己喜欢收藏电影,有时网上能找到的中文字幕文件都不满足自己电影版本。在自己下载的压制版电影中已内封非中文srt字幕时,可以选择自己将srt的时间轴转为ass并替换ass中的时间轴。自己在频繁 复制粘贴改格式的时候想起可以用Python代码完成转换这一操作&…...

蓝桥杯 枚举
例题讲解 特别数的和 #include<iostream> using namespace std; bool ifspecial(int n){while(n){if(n%100||n%101||n%102||n%109){return true;} n/10;}return false; } int main(){int n;cin>>n;int sum0;for(int i1;i<n;i){if(ifspecial(i)){sumi;}}cout&l…...

C#的MessagePack(unity)--02
高级API (MessagePackSerializer) MessagePackSerializer类是MessagePack for C# 的入口点。静态方法构成了MessagePack for C# 的主要API。 APIDescriptionSerialize<T>将一个对象图序列化为MessagePack二进制块。可以使用异步变体获取Stream。也有非泛型重载可用。De…...

MySQL数据库管理--- mysql数据库迁移-v查看报错sql
默认情况下:每个客户端连接都会在服务器进程中拥有一个线程。 每个线程相当于一个LOCALNO的oracle远程链接。 1 该连接的查询只会在这个单独的线程中执行,该线程驻留在一个内核或者CPU上,服务器维护一个 缓冲区,用于存放已就绪的线…...

基于秃鹰算法优化概率神经网络PNN的分类预测 - 附代码
基于秃鹰算法优化概率神经网络PNN的分类预测 - 附代码 文章目录 基于秃鹰算法优化概率神经网络PNN的分类预测 - 附代码1.PNN网络概述2.变压器故障诊街系统相关背景2.1 模型建立 3.基于秃鹰优化的PNN网络5.测试结果6.参考文献7.Matlab代码 摘要:针对PNN神经网络的光滑…...