>  기사  >  Java  >  SpringBoot가 파일 업로드 및 다운로드 기능을 구현하는 방법

SpringBoot가 파일 업로드 및 다운로드 기능을 구현하는 방법

WBOY
WBOY앞으로
2023-05-16 08:46:121334검색

Spring Boot 파일 업로드 및 다운로드

실제 웹 애플리케이션 개발에서 파일을 성공적으로 업로드하려면 양식의 메소드를 post로 설정하고 enctype을 multipart/form-data로 설정해야 합니다. 이 설정을 통해서만 브라우저는 선택한 파일의 바이너리 데이터를 서버로 보낼 수 있습니다.

서블릿 3.0부터 파일 업로드를 처리하는 방법이 제공됐는데, 이 파일 업로드는 자바 서블릿에서 완료해야 하는데, Spring MVC가 더 간단한 캡슐화를 제공한다. Spring MVC는 Apache Commons FileUpload 기술을 통해 MultipartResolver 구현 클래스 CommonsMultipartResolver를 구현하여 파일 업로드를 완료합니다. 따라서 Spring MVC의 파일 업로드는 Apache Commons FileUpload 구성 요소에 의존해야 합니다.

Spring MVC는 업로드된 파일을 MultipartFile 객체에 자동으로 바인딩합니다. MultipartFile은 업로드된 파일 내용, 파일 이름 등을 가져오는 메서드를 제공하고 transferTo 메서드를 통해 파일을 서버의 디스크에 업로드합니다. 다음:

  • byte[] getBytes(): 파일 데이터를 가져옵니다.

  • String getContentType(): 이미지/jpeg 등과 같은 파일 MIME 유형을 가져옵니다.

  • InputStream getInputStream(): 파일 스트림을 가져옵니다.

  • String getName(): 양식에 있는 파일 구성 요소의 이름을 가져옵니다.

  • String getOriginalFilename(): 업로드된 파일의 원본 이름을 가져옵니다.

  • long getSize(): 파일의 바이트 크기를 바이트 단위로 가져옵니다.

  • boolean isEmpty(): (선택한) 업로드 파일이 있는지 여부입니다.

  • void transferTo(File dest): 업로드된 파일을 대상 파일에 저장합니다.

Spring Boot의 spring-boot-starter-web에는 Spring MVC가 통합되어 있으므로 Spring Boot를 사용하여 파일을 업로드하는 것이 더 편리합니다. Apache Commons FileUpload 구성 요소 종속성을 도입하기만 하면 됩니다.

Example

다음은 Spring Boot 파일 업로드 및 다운로드 구현 과정을 예제를 통해 설명한다.

【예시 7】Spring Boot 파일 업로드 및 다운로드.

구체적인 구현 단계는 다음과 같습니다.

1. Apache Commons FileUpload 구성 요소 종속성을 도입합니다.

웹 애플리케이션 ch7_2의 pom.xml 파일에 Apache Commons FileUpload 구성 요소 종속성을 추가합니다.

<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <!-- 由于commons-fileupload组件不属于Spring Boot,所以需要加上版本 -->
    <version>1.4</version>
</dependency>

2. 제한

웹 애플리케이션 ch7_2에서 구성 파일 application.properties에 다음 구성을 추가하여 업로드된 파일의 크기를 제한합니다.

#上传文件时,默认单个上传文件大小是1MB,max-file-size设置单个上传文件大小
spring.servlet.multipart.max-file-size=50MB
#默认总文件大小是10MB,max-request-size设置总上传文件大小
spring.servlet.multipart.max-request-size=500MB

3. 파일 선택 뷰 페이지를 생성합니다

ch7_2 애플리케이션의 src/main/resources/templates 디렉토리에서 파일 선택 뷰 페이지 uploadFile.html을 생성합니다. 이 페이지에는 enctype 속성 값 multipart/form-data가 있는 양식 양식이 있습니다. 구체적인 코드는 다음과 같습니다.

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" th:href="@{css/bootstrap.min.css}" />
<!-- 默认访问 src/main/resources/static下的css文件夹-->
<link rel="stylesheet" th:href="@{css/bootstrap-theme.min.css}" />
</head>
<body>
<div class="panel panel-primary">
    <div class="panel-heading">
      <h4 class="panel-title">文件上传示例</h4>
    </div>
  </div>
  <div class="container">
    <div class="row">
      <div class="col-md-6 col-sm-6">
        <form class="form-horizontal" action="upload" 
method="post" enctype="multipart/form-data">
          <div class="form-group">
            <div class="input-group col-md-6">
              <span class="input-group-addon">
                <i class="glyphicon glyphicon-pencil"></i>
              </span>
              <input class="form-control" type="text"
               name="description" th:placeholder="文件描述"/>
            </div>
          </div>
          <div class="form-group">
            <div class="input-group col-md-6">
              <span class="input-group-addon">
                <i class="glyphicon glyphicon-search"></i>
              </span>
              <input class="form-control" type="file"
               name="myfile" th:placeholder="请选择文件"/>
            </div>
          </div>
          <div class="form-group">
            <div class="col-md-6">
              <div class="btn-group btn-group-justified">
                <div class="btn-group">
                  <button type="submit" class="btn btn-success">
                    <span class="glyphicon glyphicon-share"></span>
                     上传文件
                  </button>
                </div>
              </div>
            </div>
          </div>
        </form>
      </div>
    </div>
  </div>
</body>
</html>

4. 컨트롤러 만들기

ch7_2 애플리케이션의 com.ch.ch7_2.controller 패키지에 있습니다. , 컨트롤러 클래스 TestFileUpload를 만듭니다. 이 클래스에는 4가지 처리 메소드가 있는데, 하나는 인터페이스 탐색 메소드 uploadFile, 하나는 파일 업로드를 구현하는 업로드 메소드, 하나는 다운로드할 파일을 표시하는 showDownLoad 메소드, 다른 하나는 다운로드 메소드를 구현하는 다운로드 메소드입니다. 다운로드 기능. 핵심 코드는 다음과 같습니다.

@Controller
public class TestFileUpload {
  @RequestMapping("/uploadFile")
  public String uploadFile() {
    return "uploadFile";
  }
  /**
   * 上传文件自动绑定到MultipartFile对象中,
   * 在这里使用处理方法的形参接收请求参数。
     */
  @RequestMapping("/upload")
  public String upload(
      HttpServletRequest request,
      @RequestParam("description") String description,
      @RequestParam("myfile") MultipartFile myfile)
throws IllegalStateException, IOException {
    System.out.println("文件描述:" + description);
    //如果选择了上传文件,将文件上传到指定的目录uploadFiles
    if(!myfile.isEmpty()) {
      //上传文件路径
      String path = request.getServletContext().getRealPath("/uploadFiles/");
      //获得上传文件原名
      String fileName = myfile.getOriginalFilename();
      File filePath = new File(path + File.separator + fileName);
      //如果文件目录不存在,创建目录
      if(!filePath.getParentFile().exists()) {
        filePath.getParentFile().mkdirs();
      }
      //将上传文件保存到一个目标文件中
      myfile.transferTo(filePath);
    }
    //转发到一个请求处理方法,查询将要下载的文件
    return "forward:/showDownLoad";
  }
  /**
   * 显示要下载的文件
   */
  @RequestMapping("/showDownLoad")
  public String showDownLoad(HttpServletRequest request, Model model) {
    String path = request.getServletContext().getRealPath("/uploadFiles/");
    File fileDir = new File(path);
    //从指定目录获得文件列表
    File filesList[] = fileDir.listFiles();
    model.addAttribute("filesList", filesList);
    return "showFile";
  }
  /**
   * 实现下载功能
   */
  @RequestMapping("/download")
  public ResponseEntity<byte[]> download(
      HttpServletRequest request,
      @RequestParam("filename") String filename,
      @RequestHeader("User-Agent") String userAgent) throws IOException {
    //下载文件路径
    String path = request.getServletContext().getRealPath("/uploadFiles/");
    //构建将要下载的文件对象
    File downFile = new File(path + File.separator + filename);
    //ok表示HTTP中的状态是200
    BodyBuilder builder = ResponseEntity.ok();
    //内容长度
    builder.contentLength(downFile.length());
    //application/octet-stream:二进制流数据(最常见的文件下载)
    builder.contentType(MediaType.APPLICATION_OCTET_STREAM);
    //使用URLEncoder.encode对文件名进行编码
    filename = URLEncoder.encode(filename,"UTF-8");
    /**
     * 设置实际的响应文件名,告诉浏览器文件要用于“下载”和“保存”。
     * 不同的浏览器,处理方式不同,根据浏览器的实际情况区别对待。
     */
    if(userAgent.indexOf("MSIE") > 0) {
      //IE浏览器,只需要用UTF-8字符集进行URL编码
      builder.header("Content-Disposition", "attachment; filename=" + filename);
    }else {
      /**非IE浏览器,如FireFox、Chrome等浏览器,则需要说明编码的字符集
       * filename后面有个*号,在UTF-8后面有两个单引号
       */
      builder.header("Content-Disposition", "attachment; filename*=UTF-8&#39;&#39;" + filename);
    }
    return builder.body(FileUtils.readFileToByteArray(downFile));
  }
}

5. 파일 다운로드 보기 페이지 생성

ch7_2 애플리케이션의 src/main/resources/templates 디렉터리에 파일 다운로드 보기 페이지 showFile.html을 만듭니다. 핵심 코드는 다음과 같습니다.

<body>
  <div class="panel panel-primary">
    <div class="panel-heading">
      <h4 class="panel-title">文件下载示例</h4>
    </div>
  </div>
  <div class="container">
    <div class="panel panel-primary">
      <div class="panel-heading">
        <h4 class="panel-title">文件列表</h4>
      </div>
      <div class="panel-body">
        <div class="table table-responsive">
          <table class="table table-bordered table-hover">
            <tbody class="text-center">
              <tr th:each="file,fileStat:${filesList}">
                <td>
                  <span th:text="${fileStat.count}"></span>
                </td>
                <td>
                <!--file.name相当于调用getName()方法获得文件名称 -->
                  <a th:href="@{download(filename=${file.name})}">
                    <span th:text="${file.name}"></span>
                  </a>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</body>

6. 실행

먼저 Ch72Application 메인 클래스를 실행합니다. 그런 다음 http://localhost:8080/ch7_2/uploadFile을 방문하여 파일 업로드 및 다운로드를 테스트하세요.

위 내용은 SpringBoot가 파일 업로드 및 다운로드 기능을 구현하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 yisu.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제