Java 分片上传
public void uploadFile(File file) throws IOException {
int chunkSize = 1024 * 1024;
int totalChunks = (int) Math.ceil(file.length() / (double) chunkSize);
File tempDir = new File("temp");
if (!tempDir.exists()) {
tempDir.mkdir();
}
try (FileInputStream fis = new FileInputStream(file)) {
byte[] buffer = new byte[chunkSize];
for (int i = 0; i < totalChunks; i++) {
int bytesRead = fis.read(buffer);
HttpURLConnection connection = (HttpURLConnection) new URL("http://example.com/upload").openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/octet-stream");
connection.setRequestProperty("Content-Length", String.valueOf(bytesRead));
OutputStream os = connection.getOutputStream();
os.write(buffer, 0, bytesRead);
os.flush();
os.close();
InputStream is = connection.getInputStream();
byte[] response = new byte[is.available()];
is.read(response);
is.close();
File tempFile = new File(tempDir, i + ".part");
try (FileOutputStream fos = new FileOutputStream(tempFile)) {
fos.write(buffer, 0, bytesRead);
}
}
}
File outputFile = new File("output.txt");
try (FileOutputStream fos = new FileOutputStream(outputFile)) {
for (int i = 0; i < totalChunks; i++) {
File tempFile = new File(tempDir, i + ".part");
try (FileInputStream fis = new FileInputStream(tempFile)) {
byte[] buffer = new byte[chunkSize];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
}
tempFile.delete();
}
}
tempDir.delete();
}