21xrx.com
2024-12-22 22:24:34 Sunday
登录
文章检索 我的文章 写文章
Java实现文件上传的三种方式
2023-06-11 13:48:16 深夜i     --     --
Java 文件上传 三种方式

作为一名Java开发者,相信大家都会遇到文件上传的需求。Java提供了多种方式实现文件上传,下面我就来介绍一下Java实现文件上传的三种方式,希望对大家有所帮助。

1.使用Servlet实现文件上传

Servlet是Java Web开发的重要组成部分,下面我们利用Servlet来实现文件上传:


protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

  try {

    // Create a factory for disk-based file items

    DiskFileItemFactory factory = new DiskFileItemFactory();

    // Configure a repository (to ensure a secure temp location is used)

    ServletContext servletContext = this.getServletConfig().getServletContext();

    File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");

    factory.setRepository(repository);

    // Create a new file upload handler

    ServletFileUpload upload = new ServletFileUpload(factory);

    // Parse the request

    List items = upload.parseRequest(request);

    for (FileItem item : items) {

      // Process uploaded item

      if (!item.isFormField()) {

        String fileName = item.getName();

        InputStream inputStream = item.getInputStream();

        // ... Save the file to a temporary location

      }

    }

  } catch (FileUploadException e) {

    throw new ServletException("Cannot parse multipart request.", e);

  }

}

2.使用Apache Commons Fileupload实现文件上传

Apache Commons Fileupload是Apache开源组织提供的一个文件上传组件,可以方便地实现文件上传功能。下面我们利用Apache Commons Fileupload来实现文件上传:


// Import required libraries

import java.io.File;

import java.io.IOException;

import java.io.PrintWriter;

import java.util.List;

import org.apache.commons.fileupload.*;

import org.apache.commons.fileupload.disk.*;

import org.apache.commons.fileupload.servlet.*;

import javax.servlet.*;

import javax.servlet.http.*;

// Set the encoding type

String encoding = "utf-8";

if (ServletFileUpload.isMultipartContent(request)) {

  // Create a factory for disk-based file items

  DiskFileItemFactory factory = new DiskFileItemFactory();

  // Configure a repository (to ensure a secure temp location is used)

  ServletContext servletContext = this.getServletConfig().getServletContext();

  File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");

  factory.setRepository(repository);

  // Create a new file upload handler

  ServletFileUpload upload = new ServletFileUpload(factory);

  // Set the encoding type

  upload.setHeaderEncoding(encoding);

  // Parse the request

  List items = upload.parseRequest(request);

  // Process the uploaded file items

  Iterator iter = items.iterator();

  while (iter.hasNext()) {

    FileItem item = iter.next();

    if (!item.isFormField()) {

      String fileName = item.getName();

      // Write the file

      File uploadedFile = new File("D:\\" + fileName);

      item.write(uploadedFile);

    }

  }

}

3.使用SpringMVC实现文件上传

SpringMVC是一种轻量级的MVC框架,相信大家都比较熟悉。下面我们利用SpringMVC来实现文件上传:


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

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

  if (!file.isEmpty()) {

    try {

      byte[] bytes = file.getBytes();

      // store the bytes somewhere

      return "redirect:add_entry.html";

    } catch (Exception e) {

      return "You failed to upload " + file.getOriginalFilename() + " => " + e.getMessage();

    }

  } else {

    return "You failed to upload " + file.getOriginalFilename() + " because the file was empty.";

  }

}

以上就是我介绍的Java实现文件上传的三种方式,希望对大家有所帮助。

  
  

评论区

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