关于Java上传文件到服务器端的方法,主要有以下两种方式:
方式一:使用原生java.net.URLConnection API上传文件
==Step 1:== 前端HTML代码中,增加文件上传控件(input type="file")
<form method="post" action="http://localhost:8080/uploadFile" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="上传文件"/>
</form>
==Step 2:== 服务端Java代码中,使用URLConnection类实现文件上传
@PostMapping("/uploadFile")
@ResponseBody
public String uploadFile(HttpServletRequest request) throws IOException {
// 获取文件
MultipartFile file = ((MultipartHttpServletRequest) request).getFile("file");
String fileName = file.getOriginalFilename();
// 创建URL对象
URL url = new URL("http://localhost:8080/uploadFile");
// 创建连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法为POST
connection.setRequestMethod("POST");
// 设置请求头
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + "FILE_BOUNDARY");
// 开启写入模式
connection.setDoOutput(true);
connection.setDoInput(true);
// 获取输出流
OutputStream outputStream = connection.getOutputStream();
PrintWriter writer = new PrintWriter(outputStream);
// 构造文件写入请求体
writer.append("--" + "FILE_BOUNDARY" + "\r\n");
writer.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + fileName + "\"\r\n");
writer.append("Content-Type: application/octet-stream\r\n\r\n");
writer.flush();
// 写入文件
FileInputStream fis = (FileInputStream) file.getInputStream();
byte[] buffer = new byte[4096];
int length;
while ((length = fis.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
outputStream.flush();
fis.close();
// 完成请求体
writer.append("\r\n--" + "FILE_BOUNDARY" + "--\r\n");
writer.flush();
// 获取服务器响应
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder stringBuilder = new StringBuilder();
while ((line = reader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
reader.close();
connection.disconnect();
return stringBuilder.toString();
}
方式二:使用Apache HttpClient库上传文件
==Step 1:== Maven依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.10</version>
</dependency>
==Step 2:== 服务端Java代码中,使用HttpClient类实现文件上传
@PostMapping("/uploadFile")
@ResponseBody
public String uploadFile(HttpServletRequest request) throws IOException {
// 获取文件
MultipartFile file = ((MultipartHttpServletRequest) request).getFile("file");
String fileName = file.getOriginalFilename();
// 创建HttpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建HttpPost对象
HttpPost httpPost = new HttpPost("http://localhost:8080/uploadFile");
// 创建文件体
HttpEntity httpEntity = MultipartEntityBuilder.create()
.addBinaryBody("file", file.getInputStream(), ContentType.DEFAULT_BINARY, fileName)
.build();
// 设置请求体
httpPost.setEntity(httpEntity);
// 发送请求并获取响应
CloseableHttpResponse response = httpClient.execute(httpPost);
// 读取响应内容
InputStream inputStream = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
reader.close();
inputStream.close();
httpClient.close();
response.close();
return stringBuilder.toString();
}
以上就是Java上传文件到服务器端的两种方法,可以根据需求选择使用其中一种。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Java上传文件到服务器端的方法 - Python技术站