java 如何上传文件
使用 HttpURLConnection 上传文件
通过 HttpURLConnection 可以实现基本的文件上传功能。需要设置请求头为 multipart/form-data,并手动构建请求体。
String boundary = "----WebKitFormBoundary7MA4YWxkTrZu0gW";
String crlf = "\r\n";
String twoHyphens = "--";
URL url = new URL("http://example.com/upload");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
try (
OutputStream output = connection.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, StandardCharsets.UTF_8), true);
FileInputStream fileInputStream = new FileInputStream(new File("path/to/file.txt"))
) {
writer.append(twoHyphens).append(boundary).append(crlf);
writer.append("Content-Disposition: form-data; name=\"file\"; filename=\"file.txt\"").append(crlf);
writer.append("Content-Type: text/plain").append(crlf);
writer.append(crlf).flush();
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
output.flush();
writer.append(crlf).append(twoHyphens).append(boundary).append(twoHyphens).append(crlf).flush();
}
int responseCode = connection.getResponseCode();
使用 Apache HttpClient 上传文件
Apache HttpClient 提供了更简洁的 API 来处理文件上传,简化了 multipart 请求的构建过程。
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://example.com/upload");
FileBody fileBody = new FileBody(new File("path/to/file.txt"));
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addPart("file", fileBody);
HttpEntity multipart = builder.build();
httpPost.setEntity(multipart);
CloseableHttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
httpClient.close();
使用 Spring RestTemplate 上传文件
在 Spring 应用中,RestTemplate 提供了便捷的文件上传方式,特别适合与 Spring 服务端配合使用。
RestTemplate restTemplate = new RestTemplate();
String url = "http://example.com/upload";
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("file", new FileSystemResource("path/to/file.txt"));
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
ResponseEntity<String> response = restTemplate.postForEntity(url, requestEntity, String.class);
int statusCode = response.getStatusCodeValue();
使用 Java 11 HttpClient 上传文件
Java 11 引入的 HttpClient 提供了现代化的 API 来处理文件上传,支持异步操作。
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://example.com/upload"))
.header("Content-Type", "multipart/form-data")
.POST(ofMimeMultipartData(
Map.of("file", new File("path/to/file.txt").toPath()),
"boundary"))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
int statusCode = response.statusCode();
需要实现 ofMimeMultipartData 方法来构建 multipart 请求体。
文件上传注意事项
确保服务器端有足够的存储空间和处理大文件的能力。对于大文件上传,考虑实现分块上传或断点续传功能。
设置适当的超时时间,防止网络不稳定导致的上传失败。添加进度监听功能可以提供更好的用户体验。
考虑文件安全性,包括病毒扫描、文件类型验证和大小限制。服务器端应对上传文件进行严格验证,避免安全漏洞。







