java如何上传文件
文件上传的基本方法
在Java中实现文件上传通常涉及客户端和服务端的交互。以下是几种常见的方法:
使用Servlet处理文件上传
创建一个Servlet类来处理HTTP请求,通过Part或MultipartConfig注解接收文件:
@MultipartConfig
@WebServlet("/upload")
public class FileUploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Part filePart = request.getPart("file");
String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString();
InputStream fileContent = filePart.getInputStream();
Files.copy(fileContent, Paths.get("/upload/path/" + fileName));
}
}
使用Apache Commons FileUpload
添加依赖后解析multipart/form-data请求:

<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
代码示例:
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = upload.parseRequest(request);
for (FileItem item : items) {
if (!item.isFormField()) {
item.write(new File("/path/to/save/" + item.getName()));
}
}
Spring Boot中的文件上传
控制器接收文件
在Spring Boot中可使用MultipartFile接收文件:

@PostMapping("/upload")
public String handleUpload(@RequestParam("file") MultipartFile file) {
if (!file.isEmpty()) {
String uploadDir = "/var/uploads/";
Path path = Paths.get(uploadDir + file.getOriginalFilename());
Files.write(path, file.getBytes());
}
return "redirect:/";
}
配置文件限制
在application.properties中设置上传参数:
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
前端配合实现
HTML表单需设置enctype属性:
<form method="POST" action="/upload" enctype="multipart/form-data">
<input type="file" name="file" />
<button type="submit">Upload</button>
</form>
安全注意事项
- 验证文件类型和内容,避免恶意文件上传
- 限制上传文件大小,防止DoS攻击
- 使用随机生成的文件名存储,避免路径遍历漏洞
- 考虑使用云存储服务(如AWS S3)处理大文件
以上方法覆盖了从基础Servlet到Spring Boot框架的文件上传实现,开发者可根据项目需求选择合适方案。






