用java写一个分片上传大文件的代码
时间: 2024-05-18 18:18:40 浏览: 12
好的,以下是一个用 Java 实现的文件分片上传的示例代码:
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class FileUploader {
private static final int BUFFER_SIZE = 4096;
public static void upload(String targetURL, File file) throws IOException {
HttpURLConnection connection = null;
InputStream inputStream = null;
try {
// 创建连接
URL url = new URL(targetURL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setChunkedStreamingMode(BUFFER_SIZE);
// 设置请求头
connection.setRequestProperty("Content-Type", "application/octet-stream");
connection.setRequestProperty("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
// 上传文件
inputStream = new FileInputStream(file);
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
connection.getOutputStream().write(buffer, 0, bytesRead);
}
// 检查响应码
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
System.out.println("File uploaded successfully.");
} else {
System.out.println("File upload failed. Response code: " + responseCode);
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (connection != null) {
connection.disconnect();
}
}
}
}
```
使用方式:
```java
File file = new File("path/to/file");
String targetURL = "http://example.com/upload";
FileUploader.upload(targetURL, file);
```
在实际应用中,你需要把 `targetURL` 替换成你自己的上传接口地址。同时,你也可以根据具体需求修改代码中的一些参数,比如 `BUFFER_SIZE`、`Content-Type` 等。