使用spring-webmvc6實現檔案上傳

文采杰出發表於2024-07-12
  • 使用SpringMVC6版本,不需要新增以下依賴:
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.5</version>
</dependency>
  • 新建maven模組springmvc-009,pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>SpringMVC</artifactId>
        <groupId>com.powernode</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>springmvc-009</artifactId>
    <packaging>war</packaging>


    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
    </properties>
<dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>6.1.7</version>
        </dependency>

        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring6</artifactId>
            <version>3.1.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>jakarta.servlet</groupId>
            <artifactId>jakarta.servlet-api</artifactId>
            <version>6.1.0</version>
            <!--指定servlet-api有tomcat容器提供,打包時將不會將servlet-api包加入打包中-->
            <scope>provided</scope>
        </dependency>

     <!--   <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>-->

<!--        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.5.3</version>
        </dependency>-->

    </dependencies>
</project>
  • 增加web支援,web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
         version="5.0">
    <!--字元編碼過濾器-->
    <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>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!--前端控制器-->
    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:dispatcherServlet-servlet.xml</param-value>
        </init-param>
        <multipart-config>
            <!--支援最大檔案大小-->
            <max-file-size>1024000</max-file-size>
            <!--表單中多選的所有檔案上傳最大值-->
            <max-request-size>1024000</max-request-size>
            <!--設定最小檔案上傳大小-->
            <file-size-threshold>0</file-size-threshold>
        </multipart-config>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

spring配置檔案

<?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.powernode.springmvc.controller"/>

    <!--檢視控制器-->
    <!--檢視解析器-->
    <bean id="viewResolver" class="org.thymeleaf.spring6.view.ThymeleafViewResolver">
        <!--作用於檢視渲染過程中,設定檢視渲染後輸出時採用的編碼字符集-->
        <property name="characterEncoding" value="utf-8"/>
        <!--若存在多個檢視解析器,配置優先順序,值越小優先順序越高-->
        <property name="order" value="1"/>
        <property name="templateEngine">
            <bean class="org.thymeleaf.spring6.SpringTemplateEngine">
                <property name="templateResolver">
                    <bean class="org.thymeleaf.spring6.templateresolver.SpringResourceTemplateResolver">
                        <!--設定模板檔案的位置-->
                        <property name="prefix" value="/WEB-INF/templates/"/>
                        <!--設定模板檔案字尾-->
                        <property name="suffix" value=".html"/>
                        <!--設定模板型別-->
                        <property name="templateMode" value="HTML"/>
                        <!--設定模板檔案在讀取和解析過程中採用的編碼字符集-->
                        <property name="characterEncoding" value="utf-8"/>
                    </bean>
                </property>
            </bean>
        </property>
    </bean>

    <!--檢視控制器-->
    <mvc:view-controller path="/" view-name="index"/>

    <!--開啟註解驅動-->
    <mvc:annotation-driven/>

    <!--靜態資源處理-->
    <mvc:default-servlet-handler/>
</beans>
  • 配置前端首頁
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>檔案上傳與下載</title>
</head>
<body>
<h1>檔案上傳與下載</h1>
<hr>
<form th:action="@{/fileup}" method="post" enctype="multipart/form-data">
    檔案上傳: <input type="file" name="fileName"><br>
    <input type="submit" value="上傳">
</form>
</body>
</html>
  • 配置FileController
package com.powernode.springmvc.controller;

import jakarta.servlet.ServletContext;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;


@RestController
public class FileController {
    @RequestMapping(value = "/fileup",method = RequestMethod.POST)
    public String fileup(@RequestParam("fileName") MultipartFile multipartFile, HttpServletRequest request) throws IOException {
        String name = multipartFile.getName();
        System.out.println(name);//獲取的名字是fineName
        String originalFilename = multipartFile.getOriginalFilename();
        System.out.println(originalFilename);//獲取的名字是檔案原名
        Path path = Paths.get(name);
        System.out.println("path:"+ path);
        //獲取輸入流
        InputStream inputStream = multipartFile.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(inputStream);

        //輸出流
        ServletContext servletContext = request.getServletContext();
        String realPath = servletContext.getRealPath("/upload");
        File file = new File(realPath);
        if (!file.exists()){
            file.mkdirs();
        }
        File destFile = new File(file.getAbsolutePath() + "/" + originalFilename);


        //輸出流
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile));

        //一邊讀一邊寫
        byte[] bytes = new byte[1024 * 10];
        int readCount = 0;
        while((readCount = bis.read(bytes)) != -1){
            bos.write(bytes, 0,readCount);
        }

        bos.flush();
        bos.close();
        bis.close();
        return "ok";
    }
}

最後重啟tomcat,測試

成功上傳到伺服器指定地址

相關文章