下面从服务器和客户端两个角度,分别讲解Java实现文件上传的完整攻略。
一、服务器方案
1.1 前置准备
首先,我们需要引入Java的文件上传相关依赖包:commons-fileupload和commons-io。这两个包的作用是支持多种文件上传方式,并且后者还提供了一些方便的工具类来处理文件操作。
引入依赖参考pom.xml文件配置:
<dependencies>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
</dependencies>
1.2 服务器端代码实现
服务器端代码实现大致分成以下四个步骤:
- 创建Servlet,配置上传文件的相关参数:
@WebServlet("/upload")
@MultipartConfig(
location = "/tmp", // 指定上传文件的目录
maxFileSize = 1024 * 1024 * 10, // 最大文件上传大小
maxRequestSize = 1024 * 1024 * 50, // 最大请求体大小
fileSizeThreshold = 1024 * 1024, // 文件大小临界值(当文件大小超过这个值时,会写入磁盘)
)
public class UploadServlet extends HttpServlet {
// ...
}
- 调用request.getPart()方法获取上传文件的part对象,然后使用InputStream获取文件流和part.getSubmittedFileName()获取文件名:
Part partFile = request.getPart("file");
String fileName = partFile.getSubmittedFileName();
InputStream inputStream = partFile.getInputStream();
- 使用Apache commons-io的FileUtils.copyInputStreamToFile()方法将inputStream中的文件流写入到目标文件:
File targetFile = new File(uploadPath, fileName);
FileUtils.copyInputStreamToFile(inputStream, targetFile);
- 处理上传过程中出现的异常或者错误,并返回上传结果:
response.setContentType("application/json;charset=UTF-8");
String json = "{\"message\":\"ok\"}";
response.getWriter().write(json);
1.3 示例
下面是一个基于SpringBoot的上传文件服务器的示例代码:
@RestController
public class FileController {
@PostMapping(value="/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<Object> upload(@RequestParam("file") MultipartFile file) throws IOException {
File targetFile = new File("/tmp/" + file.getOriginalFilename());
file.transferTo(targetFile);
return ResponseEntity.ok().build();
}
}
二、客户端方案
2.1 前置准备
在客户端实现文件上传的过程中,我们需要使用Java的HttpURLConnection和BufferedReader类。具体来说,我们先构造HttpURLConnection对象,并设置相关的属性,比如请求的方式和请求头参数。然后,将要上传的文件读入内存中,然后构造一个OutputStream对象并将文件写入请求中。最后,处理服务器端的返回结果。
2.2 客户端代码实现
客户端上传文件通常分成以下三个步骤:
- 配置请求参数:
URL url = new URL("http://localhost:8080/upload");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
connection.setDoOutput(true);
- 构造表单数据:
OutputStream outputStream = connection.getOutputStream();
String formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"%s\"\r\n\r\n%s";
outputStream.write(String.format(formdataTemplate, "name", "testname").getBytes("utf-8"));
outputStream.write(String.format(formdataTemplate, "email", "testemail").getBytes("utf-8"));
outputStream.write(String.format(formdataTemplate, "file", file.getName()).getBytes("utf-8"));
- 上传文件并处理结果:
FileInputStream inputStream = new FileInputStream(file);
int bytesRead = -1;
byte[] buffer = new byte[4096];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.write("\r\n--".getBytes("utf-8"));
outputStream.write(boundary.getBytes("utf-8"));
outputStream.write("--\r\n".getBytes("utf-8"));
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
String line = "";
while ((line = in.readLine()) != null) {
System.out.println(line);
}
inputStream.close();
outputStream.flush();
outputStream.close();
2.3 示例
下面是一个基于Java URL的上传文件的客户端示例代码:
public class FileUploadTest {
public static void main(String[] args) throws Exception {
String boundary = UUID.randomUUID().toString();
File file = new File("test.jpg");
URL url = new URL("http://localhost:8080/upload");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
connection.setDoOutput(true);
OutputStream outputStream = connection.getOutputStream();
String formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"%s\"\r\n\r\n%s";
outputStream.write(String.format(formdataTemplate, "name", "testname").getBytes("utf-8"));
outputStream.write(String.format(formdataTemplate, "email", "testemail").getBytes("utf-8"));
outputStream.write(String.format(formdataTemplate, "file", file.getName()).getBytes("utf-8"));
FileInputStream inputStream = new FileInputStream(file);
int bytesRead = -1;
byte[] buffer = new byte[4096];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.write("\r\n--".getBytes("utf-8"));
outputStream.write(boundary.getBytes("utf-8"));
outputStream.write("--\r\n".getBytes("utf-8"));
inputStream.close();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
String line = "";
while ((line = in.readLine()) != null) {
System.out.println(line);
}
outputStream.flush();
outputStream.close();
}
}
这篇文章介绍了常见的文件上传操作。在实际开发中,我们可以根据业务需求进行修改和扩展。在此基础上,还可以加入安全认证和限流等措施加强上传文件的安全性和稳定性。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Java实现文件上传服务器和客户端 - Python技术站