下面是一个简单的实现Java断点续传上传功能的代码示例,其中使用了HttpURLConnection和RandomAccessFile类:
public class ResumableUploader {
private static final int BUFFER_SIZE = 4096;
private static final String FILE_PATH = "yourFilePath";
private static final String UPLOAD_URL = "yourUploadUrl";
private static final int MAX_NUM_RETRIES = 5;
public static void main(String[] args) throws Exception {
File file = new File(FILE_PATH);
// 获取文件大小
long fileSize = file.length();
// 创建 HttpURLConnection
HttpURLConnection conn = (HttpURLConnection) new URL(UPLOAD_URL).openConnection();
// 设置请求头信息
conn.setRequestMethod("POST");
conn.setConnectTimeout(10000);
conn.setReadTimeout(10000);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/octet-stream");
conn.setRequestProperty("Content-Length", String.valueOf(fileSize));
// 获取已上传的文件大小
long uploadedSize = 0L;
String range = conn.getRequestProperty("Range");
if (range != null) {
String[] rs = range.substring("bytes=".length()).split("-");
uploadedSize = Long.parseLong(rs[0]);
}
// 设置请求体
OutputStream os = conn.getOutputStream();
RandomAccessFile raf = new RandomAccessFile(file, "r");
raf.seek(uploadedSize);
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = raf.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
raf.close();
// 处理响应
int responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED) {
System.out.println("文件上传成功!");
} else {
System.out.println("文件上传失败,响应码:" + responseCode);
int numRetries = 0;
while (responseCode >= 500 && responseCode < 600 && numRetries < MAX_NUM_RETRIES) {
System.out.println("服务器错误,正在重新上传...");
Thread.sleep(5000);
conn = (HttpURLConnection) new URL(UPLOAD_URL).openConnection();
conn.setRequestProperty("Content-Type", "application/octet-stream");
conn.setRequestProperty("Content-Length", String.valueOf(fileSize));
conn.setRequestProperty("Range", "bytes=" + uploadedSize + "-");
os = conn.getOutputStream();
raf = new RandomAccessFile(file, "r");
raf.seek(uploadedSize);
buffer = new byte[BUFFER_SIZE];
bytesRead = 0;
while ((bytesRead = raf.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
raf.close();
responseCode = conn.getResponseCode();
numRetries++;
}
if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED) {
System.out.println("文件上传成功!");
} else {
System.out.println("文件上传失败,响应码:" + responseCode);
}
}
}
}
注:该代码仅供参考,实际使用时需要根据具体业务需求进行修改。
参考文章:http://blog.ncmem.com/wordpress/2023/10/23/java-实现断点续传的上传功能/