21xrx.com
2024-09-17 03:46:17 Tuesday
登录
文章检索 我的文章 写文章
Java实现文件上传的三种方式
2023-06-15 09:02:11 深夜i     --     --
Java 文件上传 Servlet Apache

我最近在一个Web项目中遇到了需要实现文件上传的需求,经过一番调研之后,我总结了几种Java实现文件上传的方式,现在跟大家分享一下。

1. Servlet实现文件上传

这是最基本的实现方式,我们可以在Servlet中使用request.getPart("file")获取到上传的文件,然后再通过IO流将文件保存到服务器中。


Part filePart = request.getPart("file");

InputStream fileContent = filePart.getInputStream();

File targetFile = new File("/path/to/save/file");

OutputStream outStream = new FileOutputStream(targetFile);

byte[] buffer = new byte[4096];

int bytesRead = -1;

while ((bytesRead = fileContent.read(buffer)) != -1) {

  outStream.write(buffer, 0, bytesRead);

}

outStream.flush();

outStream.close();

2. Apache Commons FileUpload实现文件上传

Apache Commons FileUpload是一个常用的Java文件上传组件,它提供了一系列的API以简化文件上传的实现。我们可以通过下面的代码来实现文件上传:


DiskFileItemFactory factory = new DiskFileItemFactory();

ServletFileUpload fileUpload = new ServletFileUpload(factory);

List items = fileUpload.parseRequest(request);

for (FileItem item : items) {

  if (!item.isFormField()) {

    InputStream fileContent = item.getInputStream();

    File targetFile = new File("/path/to/save/file");

    OutputStream outStream = new FileOutputStream(targetFile);

    byte[] buffer = new byte[4096];

    int bytesRead = -1;

    while ((bytesRead = fileContent.read(buffer)) != -1) {

      outStream.write(buffer, 0, bytesRead);

    }

    outStream.flush();

    outStream.close();

  }

}

3. Spring MVC实现文件上传

Spring MVC提供了方便的文件上传功能,我们只需要在Controller中使用@RequestPart注解即可获取到上传的文件流。


@RequestMapping(value = "/upload", method = RequestMethod.POST)

public String uploadFile(@RequestPart("file") MultipartFile file) throws IOException {

  File targetFile = new File("/path/to/save/file");

  OutputStream outStream = new FileOutputStream(targetFile);

  byte[] buffer = new byte[4096];

  int bytesRead = -1;

  InputStream fileContent = file.getInputStream();

  while ((bytesRead = fileContent.read(buffer)) != -1) {

    outStream.write(buffer, 0, bytesRead);

  }

  outStream.flush();

  outStream.close();

  return "success";

}

综上所述,我们可以使用Servlet、Apache Commons FileUpload或者Spring MVC来实现Java文件上传。每一种方式都有其优缺点,需要根据实际情况选择最适合的实现方式。

Commons FileUpload、Spring MVC

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复