21xrx.com
2025-03-27 11:10:35 Thursday
文章检索 我的文章 写文章
我最近在做一个项目
2023-06-10 22:09:51 深夜i     9     0

我最近在做一个项目,在其中需要实现文件的上传功能。在学习过程中,我了解到了java实现文件上传的三种方式:基于Servlet API、基于Apache Commons FileUpload和基于Spring MVC。下面我将详细介绍这三种方式的实现以及代码例子。

1. 基于Servlet API的文件上传

通过Servlet API,我们可以使用request.getPart()方法获取上传的文件,然后通过输入流和输出流实现文件的存储。

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  String filePath = "C:\\temp\\";
  Part filePart = request.getPart("file");
  String fileName = getSubmittedFileName(filePart);
  File file = new File(filePath + fileName);
  try (InputStream fileContent = filePart.getInputStream(); FileOutputStream fos = new FileOutputStream(file)) {
    int read = 0;
    final byte[] bytes = new byte[1024];
    while ((read = fileContent.read(bytes)) != -1) {
      fos.write(bytes, 0, read);
    }
  }
  response.getWriter().println("file uploaded successfully");
}

2. 基于Apache Commons FileUpload的文件上传

Apache Commons FileUpload是一个流行的开源组件,它提供了上传多文件的功能。使用这个组件,我们需要在pom.xml中添加如下dependency:

xml

  
  commons-fileupload
 
  
  commons-fileupload
 
  
  1.3.3

然后,在Java代码中,我们需要创建一个FileItemFactory对象和一个ServletFileUpload对象,以便提供文件上传的功能。

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  String filePath = "C:\\temp\\";
  ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
  try {
    List
  items = upload.parseRequest(request);
 
    for (FileItem item : items) {
      if (item.isFormField())
        //处理表单域
       else {
        String fileName = new File(item.getName()).getName();
        File file = new File(filePath + fileName);
        item.write(file);
      }
    }
  } catch (Exception e) {
    e.printStackTrace();
  }
  response.getWriter().println("file uploaded successfully");
}

3. 基于Spring MVC的文件上传

Spring MVC是一个流行的java web框架,它提供了文件上传的支持。使用这种方法,我们需要在pom.xml中添加如下dependency:

xml

  
  org.springframework
 
  
  spring-web
 
  
  5.1.5.RELEASE

然后,在Spring MVC的控制器中,我们需要注入MultipartFile对象以实现文件的上传:

@PostMapping("/upload")
public ResponseEntity handleFileUpload(@RequestParam("file") MultipartFile file) {
  String fileName = StringUtils.cleanPath(file.getOriginalFilename());
  try {
    // 存储文件
    Path targetLocation = Paths.get("C:\\temp\\" + fileName);
    Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
  } catch (IOException ex) {
    ex.printStackTrace();
  }
  return ResponseEntity.ok().body("file uploaded successfully");
}

综上所述,这三种方法都可以实现文件上传的功能。基于Servlet API方法适用于简单的文件上传,而基于Apache Commons FileUpload和基于Spring MVC的方法则更加通用。具体选择哪一种方法,需要根据开发的需求和情况做出取舍。

笔者建议掌握最后两种方法,他们更加通用和灵活。

  
  

评论区