java如何上传文件到服务器
使用HttpURLConnection上传文件
创建HttpURLConnection连接,设置请求方法为POST,并启用输出流。设置合适的请求头,如Content-Type为multipart/form-data。通过输出流写入文件数据,构建符合HTTP协议的multipart请求体。
String boundary = "----WebKitFormBoundary7MA4YWxkTrZu0gW";
HttpURLConnection connection = (HttpURLConnection) new URL("http://example.com/upload").openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
try (OutputStream output = connection.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, "UTF-8"))) {
// 写入文件部分
writer.append("--" + boundary).append("\r\n");
writer.append("Content-Disposition: form-data; name=\"file\"; filename=\"file.txt\"").append("\r\n");
writer.append("Content-Type: text/plain").append("\r\n\r\n");
writer.flush();
Files.copy(Paths.get("path/to/file.txt"), output);
output.flush();
// 结束标记
writer.append("\r\n--" + boundary + "--\r\n").flush();
}
使用Apache HttpClient上传文件
引入Apache HttpClient库,创建CloseableHttpClient实例。构建MultipartEntityBuilder添加文件部分,创建HttpPost请求并设置实体。执行请求并处理响应。

CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost uploadFile = new HttpPost("http://example.com/upload");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addPart("file", new FileBody(new File("path/to/file.txt")));
HttpEntity multipart = builder.build();
uploadFile.setEntity(multipart);
CloseableHttpResponse response = httpClient.execute(uploadFile);
使用Spring RestTemplate上传文件
在Spring项目中配置RestTemplate,创建MultiValueMap封装文件数据。使用postForEntity或exchange方法发送请求,注意设置正确的Content-Type头。
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);
使用WebSocket上传文件
建立WebSocket连接后,将文件转换为字节数组或分片发送。适合需要实时传输或大文件分块上传的场景,需服务端支持WebSocket协议。

ByteBuffer buffer = ByteBuffer.wrap(Files.readAllBytes(Paths.get("path/to/file.txt")));
session.getBasicRemote().sendBinary(buffer);
处理服务器响应
检查HTTP响应码,200系列表示成功。读取响应内容获取服务器返回的信息,如文件存储路径或处理结果。确保关闭所有资源防止内存泄漏。
int statusCode = connection.getResponseCode();
if (statusCode == HttpURLConnection.HTTP_OK) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
String response = reader.lines().collect(Collectors.joining());
}
}
错误处理与重试机制
捕获IOException处理网络异常,实现重试逻辑应对临时故障。添加超时设置防止长时间等待,如连接超时和读取超时。
connection.setConnectTimeout(5000);
connection.setReadTimeout(30000);
安全注意事项
使用HTTPS协议加密传输,验证服务器证书。对敏感文件进行客户端加密,服务端解密。限制上传文件类型和大小,防止恶意文件上传攻击。






