java如何上传附件
使用Servlet处理文件上传
在Java Web应用中,Servlet是处理文件上传的常见方式。需要创建一个Servlet类,并通过@MultipartConfig注解或配置web.xml来支持文件上传。
@WebServlet("/upload")
@MultipartConfig
public class FileUploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Part filePart = request.getPart("file");
String fileName = filePart.getSubmittedFileName();
InputStream fileContent = filePart.getInputStream();
// 保存文件到服务器
Files.copy(fileContent, Paths.get("/path/to/save/" + fileName));
response.getWriter().print("File uploaded successfully");
}
}
使用Spring Boot处理文件上传
Spring Boot简化了文件上传的处理流程。通过MultipartFile接口可以轻松获取上传的文件内容。
@RestController
public class FileUploadController {
@PostMapping("/upload")
public String handleFileUpload(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return "File is empty";
}
try {
byte[] bytes = file.getBytes();
Path path = Paths.get("/path/to/save/" + file.getOriginalFilename());
Files.write(path, bytes);
return "File uploaded successfully";
} catch (IOException e) {
return "Upload failed: " + e.getMessage();
}
}
}
使用Apache Commons FileUpload
对于非Spring项目,可以使用Apache Commons FileUpload库处理文件上传。需要添加依赖:
<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()) {
String fileName = new File(item.getName()).getName();
File uploadedFile = new File("/path/to/save/" + fileName);
item.write(uploadedFile);
}
}
前端HTML表单
无论后端采用哪种技术,前端HTML表单需要设置enctype="multipart/form-data":
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<button type="submit">Upload</button>
</form>
文件大小限制
在Servlet中可以通过@MultipartConfig的maxFileSize参数限制文件大小:
@MultipartConfig(maxFileSize = 1024 * 1024 * 5) // 5MB
在Spring Boot中可以在application.properties中配置:
spring.servlet.multipart.max-file-size=5MB
spring.servlet.multipart.max-request-size=5MB
安全性考虑
文件上传功能需要特别注意安全性:

- 验证文件类型,防止上传可执行文件
- 限制文件大小,防止DoS攻击
- 对上传的文件进行病毒扫描
- 避免使用用户提供的文件名直接保存,防止路径遍历攻击
以上方法涵盖了从传统Servlet到现代Spring Boot的文件上传实现,开发者可以根据项目需求选择合适的技术方案。






