21xrx.com
2024-09-17 04:16:14 Tuesday
登录
文章检索 我的文章 写文章
Java实现文件上传的三种方法
2023-06-15 12:47:01 深夜i     --     --
Servlet HttpServletRequest getPart

想要实现在Java中上传文件,有很多种方法。本文将为大家介绍三种实现文件上传的方法,分别是使用Servlet、SpringMVC和Apache Commons FileUpload。以下是具体的实现过程和代码案例。

一、使用Servlet

在Servlet中使用的是HttpServletRequest对象的getPart方法,通过这个方法能够得到上传的文件。具体代码如下:


protected void doPost(HttpServletRequest request, HttpServletResponse response)

  throws ServletException, IOException {

 // 获取上传的文件

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

 // 将文件保存在指定目录

 InputStream fileContent = filePart.getInputStream();

 Files.copy(fileContent, Paths.get("C:/upload/" + filePart.getSubmittedFileName()));

}

二、使用SpringMVC

在SpringMVC中实现文件上传要比Servlet简单一些,只需要添加MultipartFile对象即可。具体示例代码如下:


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

public String handleFileUpload(@RequestParam("file") MultipartFile file,

                RedirectAttributes redirectAttributes) {

 // 判断文件是否为空

 if (file.isEmpty()) {

  redirectAttributes.addFlashAttribute("message", "请选择一个文件进行上传");

  return "redirect:uploadStatus";

 }

 try {

  // 将文件保存在指定目录

  byte[] bytes = file.getBytes();

  Path path = Paths.get("C:/upload/" + file.getOriginalFilename());

  Files.write(path, bytes);

  redirectAttributes.addFlashAttribute("message", "文件上传成功!");

 } catch (IOException e) {

  e.printStackTrace();

 }

 return "redirect:/uploadStatus";

}

关键词:SpringMVC、MultipartFile、getBytes。

三、使用Apache Commons FileUpload

Apache Commons FileUpload提供了上传文件的解决方案。具体的代码如下:


protected void doPost(HttpServletRequest request, HttpServletResponse response)

    throws ServletException, IOException {

 // 创建FileItemFactory实例

 DiskFileItemFactory factory = new DiskFileItemFactory();

 // 设置缓冲区大小

 factory.setSizeThreshold(1024 * 1024);

 // 设置临时文件目录

 factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

 // 创建ServletFileUpload实例

 ServletFileUpload upload = new ServletFileUpload(factory);

 // 解析上传请求

 List items = upload.parseRequest(request);

 // 处理上传的文件

 for (FileItem item : items) {

  // 判断是否为文件类型

  if (!item.isFormField()) {

   // 获取文件名

   String fileName = new File(item.getName()).getName();

   // 设置文件存储路径

   String filePath = "C:/upload/" + fileName;

   File storeFile = new File(filePath);

   // 在控制台输出文件的上传路径

   System.out.println(filePath);

   // 保存文件到硬盘

   item.write(storeFile);

  }

 }

}

关键词:Apache Commons FileUpload、DiskFileItemFactory、ServletFileUpload。

通过本文的介绍,相信大家对Java中文件上传的实现方式有了更加深入的了解。具体实现方式可以根据自己的需求选择。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复
    相似文章