SpringMVC 파일 업로드 및 다운로드 실현

본 논문 의 사례 는 SpringMVC 가 파일 업로드 와 다운 로드 를 실현 하 는 구체 적 인 코드 를 공유 하여 여러분 께 참고 하 시기 바 랍 니 다.구체 적 인 내용 은 다음 과 같 습 니 다.
0.환경 준비
1.maven 의존

<dependencies>
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter-api</artifactId>
      <version>5.7.0</version>
      <scope>test</scope>
    </dependency>


    <!-- servlet   -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>

    <!-- springMVC   -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.2.6.RELEASE</version>
    </dependency>

    <!--      jar  -->
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.8.0</version>
    </dependency>
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.3</version>
</dependency>
2.springConfig。xml 프로필

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!--          -->
    <context:component-scan base-package="com.compass.file"></context:component-scan>

    <!--     springMVC     -->
    <bean  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--  :       -->
        <property name="prefix" value="/WEB-INF/view/" />
        <!--  :        -->
        <property name="suffix" value=".jsp" />
    </bean>

    <!--  JSON   (Jackson)-->
    <mvc:annotation-driven />

<!--           -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--          -->
        <property name="defaultEncoding" value="utf-8"> </property>
<!--                   -1       maxUploadSizePerFile            , maxUploadSize             -->
        <property name="maxUploadSizePerFile" value="-1"> </property>

 <!-- ,                ,               1M(1*1024*1024) -->
        <property name="maxUploadSize" value="1048576"/>

    </bean>

</beans>
3.web.xml 설정

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
  <!--   springMvc      DispatcherServlet -->
  <servlet>
    <servlet-name>web</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springConfig.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>web</servlet-name>
    <url-pattern>*.mvc</url-pattern>
  </servlet-mapping>

  <!--          ,  post         -->
  <filter>
    <filter-name>characterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>utf-8</param-value>
    </init-param>
    <init-param>
      <param-name>forRequestEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
    <init-param>
      <param-name>forResponseEncoding</param-name>
      <param-value>true</param-value>
    </init-param>

  </filter>
  <filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>
1.파일 업로드
파일 업로드 방식 은 세 가지 로 나 뉜 다.
단일 파일 단일 필드
여러 파일 단일 필드여러 파일 다 중 필드
주의 점:
1.제출 방식 이 폼 인 post 요청
2、from 속성 중 enctype="multipart/form-data"가 있어 야 합 니 다.
3.단일 필드 다 중 파일 이 라면:입력 상자 의 속성 은:multiple="multiple"이 어야 합 니 다.
4.폼 의 속성 name 은 백 엔 드 매개 변수 와 일치 해 야 합 니 다.
1.전단 코드

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>    </title>
</head>
<body>

<div>
    <p style="text-align: center">    (         )</p>
    <form action="${pageContext.request.contextPath}/uploadFile1.mvc" method="post"  enctype="multipart/form-data">
        <input type="file" name="file">
        <input type="submit" value="  ">
    </form>
</div>

<div>
    <p style="text-align: center">    (        )</p>
    <form action="${pageContext.request.contextPath}/uploadFile2.mvc" method="post"  enctype="multipart/form-data">
        <input type="file" name="file" multiple="multiple">
        <input type="submit" value="  ">
    </form>
</div>


<div>
    <p style="text-align: center">    (        )</p>
    <form action="${pageContext.request.contextPath}/uploadFile2.mvc" method="post"  enctype="multipart/form-data">
        <input type="file" name="file" >
        <input type="file" name="file" >
        <input type="submit" value="  ">
    </form>
</div>

</body>
</html>
2.백 엔 드 코드

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;

/**
 * @author compass
 * @version 1.0
 * @date 2021-05-11 14:33
 */
@Controller
public class UploadIFileController {

    //         
    @PostMapping("/uploadFile1.mvc")
     public ModelAndView uploadFile1(MultipartFile file, HttpSession session) throws IOException {

        ModelAndView view = new ModelAndView();
        //       
        String filename=file.getOriginalFilename();
        System.out.println("    :"+filename);
        if (!file.isEmpty()){
            //        
            if (filename.endsWith(".jpg")||filename.endsWith(".png")||filename.endsWith(".txt"));
            //         
            String savePath="C:\\Users\\14823\\IdeaProjects\\springMVC\\fileupload\\src\\main\\webapp\\WEB-INF\\file";
            File srcFile = new File(savePath,filename);
            //         
            file.transferTo(srcFile);
            view.setViewName("forward:/uploadSuccess.jsp");
        }else {
            view.setViewName("forward:/uploadFailed.jsp");
        }
        return view;
    }

    //        
    @PostMapping("/uploadFile2.mvc")
    public ModelAndView uploadFile2(MultipartFile[] file,HttpSession session) throws IOException {

        ModelAndView view = new ModelAndView();
        //         
        String savePath="C:\\Users\\14823\\IdeaProjects\\springMVC\\fileupload\\src\\main\\webapp\\WEB-INF\\file";
        String[] filenames = new String[file.length];
        //                             
        for (int i = 0; i <filenames.length ; i++) {
            //              
            if (!file[i].isEmpty()){
               String filename=file[i].getOriginalFilename();
               //       
               if (filename.endsWith(".txt")||filename.endsWith(".jpg")||filename.endsWith(".png")){
                   //         
                   File srcFile = new File(savePath, filename);
                   //         
                   file[i].transferTo(srcFile);
                   view.setViewName("forward:/uploadSuccess.jsp");
               }else {
                   view.setViewName("forward:/uploadSuccess.jsp");
               }

            }else {
                view.setViewName("forward:/uploadFailed.jsp");
            }

        }
        return view;
    }
}
2.파일 다운로드
파일 아래 두 가지 상황 으로 나 뉜 다.
  • 파일 이름 은 순수한 영문 자모의
  • 파일 이름 은 중국어 로 처리 하지 않 으 면 번 거 로 워 집 니 다
  • 1.전단 코드
    
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>    </title>
    </head>
    <body>
    <h1 style="text-align: center"><a href="${pageContext.request.contextPath}/download1.mvc?filename=preview.jpg" rel="external nofollow" >    (     )</a></h1>
    <h1 style="text-align: center"><a href="${pageContext.request.contextPath}/download2.mvc?filename=    .txt" rel="external nofollow" >    (    )</a></h1>
    </body>
    </html>
    2.백 엔 드 코드
    
    /**
     * @author compass
     * @version 1.0
     * @date 2021-05-11 15:23
     */
    @Controller
    public class DownloadController {
    
        //          
        @GetMapping("/download1.mvc")
        public ResponseEntity <byte[]> fileDownload1(String filename,HttpServletRequest request) throws IOException {
    
            String path="C:\\Users\\14823\\IdeaProjects\\springMVC\\fileupload\\src\\main\\webapp\\WEB-INF\\file\\";
            File file = new File(path,filename);
            HttpHeaders header = new HttpHeaders();
            header.setContentDispositionFormData("attachment",filename);
            header.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            ResponseEntity<byte[]> result = new ResponseEntity<>(FileUtils.readFileToByteArray(file), header, HttpStatus.OK);
            return result;
        }
    
        //         
        @GetMapping("/download2.mvc")
        public ResponseEntity <byte[]> fileDownload2(String filename,HttpServletRequest request) throws IOException {
    
            System.out.println(filename);
            String path="C:\\Users\\14823\\IdeaProjects\\springMVC\\fileupload\\src\\main\\webapp\\WEB-INF\\file\\";
            filename = filename.replace("_", "%");
            filename= URLDecoder.decode(filename,"UTF-8");
            String downloadFile="";
            if (request.getHeader("USER-AGENT").toLowerCase().indexOf("msie")>0){
                filename= URLEncoder.encode(filename,"UTF-8");
                downloadFile=filename.replaceAll("+","%20");
            }else {
                downloadFile=new String(filename.getBytes("UTF-8"),"ISO-8859-1");
            }
            File file = new File(path,filename);
            HttpHeaders header = new HttpHeaders();
            header.setContentDispositionFormData("attachment",downloadFile);
            header.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            ResponseEntity<byte[]> result = new ResponseEntity<>(FileUtils.readFileToByteArray(file), header, HttpStatus.OK);
            return result;
        }
    
    }
    이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

    좋은 웹페이지 즐겨찾기