Java 上传大文件的代码
时间: 2023-08-07 14:07:42 浏览: 90
java上传文件代码
上传大文件的代码可以通过分块上传来实现,以下是一个示例:
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class FileUploader {
private static final int CHUNK_SIZE = 512 * 1024; // 512KB
public static void upload(File file, String uploadUrl) throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
// 1. 分块上传
FileInputStream inputStream = new FileInputStream(file);
byte[] buffer = new byte[CHUNK_SIZE];
int bytesRead = -1;
int chunkIndex = 0;
while ((bytesRead = inputStream.read(buffer)) != -1) {
String chunkData = Base64.encodeBase64String(buffer);
String chunkUrl = uploadUrl + "?chunkIndex=" + chunkIndex;
HttpPost chunkUploadRequest = new HttpPost(chunkUrl);
chunkUploadRequest.setHeader("Content-Type", "application/json;charset=UTF-8");
chunkUploadRequest.setEntity(new StringBody(chunkData, ContentType.APPLICATION_JSON));
HttpResponse chunkUploadResponse = httpClient.execute(chunkUploadRequest);
if (chunkUploadResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
throw new IOException("Failed to upload chunk " + chunkIndex + ", status code: " + chunkUploadResponse.getStatusLine().getStatusCode());
}
chunkIndex++;
}
inputStream.close();
// 2. 合并分块
String mergeUrl = uploadUrl + "?merge=true";
HttpPost mergeRequest = new HttpPost(mergeUrl);
HttpResponse mergeResponse = httpClient.execute(mergeRequest);
HttpEntity mergeEntity = mergeResponse.getEntity();
if (mergeResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
EntityUtils.consume(mergeEntity);
throw new IOException("Failed to merge chunks, status code: " + mergeResponse.getStatusLine().getStatusCode());
}
EntityUtils.consume(mergeEntity);
httpClient.close();
}
}
```
这个代码示例使用了 Apache HttpComponents 库来进行 HTTP 请求,其中 `CHUNK_SIZE` 是指每个分块的大小,根据需要可以调整。具体的上传 URL 需要根据实际情况进行替换。
阅读全文