Spring Boot2.x文件上传简单案例

Spring Boot文件上传简单案例

本案例环境:

  1. SpringBoot: 2.3.0.RELEASE
  2. JDK: 1.8
  3. 模板: thymeleaf

1. 创建工程

在IDEA中通过SpringBoot初始化向导创建一个名称为yuan-fileupload的工程

2. 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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>org.yuan</groupId>
    <artifactId>yuan-fileupload</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>yuan-fileupload</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.2</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.4</version>
        </dependency>



        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

2. application.yml

server:
  port: 8085
spring:
  servlet:
    multipart:
      max-file-size: 1GB # 单个文件上传的大小
      max-request-size: 1GB # 上传的总文件大小

3.前端fileupload.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>文件上传案例</title>
</head>
<body>
    
<form method="post" enctype="multipart/form-data" th:action="${#httpServletRequest.getContextPath()}+'/fileUpload'">
    文件1: <input type="file" name="files"><br>
    文件2: <input type="file" name="files"><br>
    <input type="submit" value="上传">
</form>
</body>
</html>

4. 后端控制器

FileUploadController.Java如下:

package org.yuan.yuanfileupload.fileupload;

import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.yuan.yuanfileupload.utils.ResultMsg;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * <p>
 * Description: 文件上传简单案例 <br>
 * <p>
 * Author:jinshengyuan <br>
 * Datetime: 2020/5/24 14:55
 * </p>
 *
 * @since 2020/5/24 14:55
 */
@Controller
public class FileUploadController {

    /**
     * <p>
     * Description: 跳转至文件上传页面的handler <br>
     * <p>
     * Author:jinshengyuan <br>
     * Datetime: 2020/5/24 14:56
     * </p>
     *
     * @return 跳转的模板名称
     * @since 2020/5/24 14:56
     */
    @RequestMapping("/initUpload")
    public String initUpload() {
        return "fileUpload";
    }


    /**
     * <p>
     * Description: 文件上传方法<br>
     * <p>
     * Author:jinshengyuan <br>
     * Datetime: 2020/5/24 14:57
     * </p>
     *
     * @return 返回上传后的处理结果
     * @since 2020/5/24 14:57
     */
    @ResponseBody
    @RequestMapping("/fileUpload")
    public ResultMsg fileUpload(MultipartFile[] files, HttpServletRequest request) throws Exception {
        for (MultipartFile file : files) {
            String contentType = file.getContentType();
            String originalFilename = file.getOriginalFilename();
            String name = file.getName();
            System.out.println("contentType:" + contentType);
            System.out.println("originalFilename:" + originalFilename);
            System.out.println("name:" + name);
            //文件名不为空则上传
            if (!StringUtils.isEmpty(originalFilename)) {
                //文件存放位置
                //1.传统的方式获取服务器跟目录下的fileUpload路径
                //String realPath = request.getServletContext().getRealPath("/fileUpload");
                //2.Springboot项目中获取resource/static/fileupload路径
                String uploadPath = ResourceUtils.getURL("classpath:").getPath() + "static/fileUpload/";
                System.out.println("uploadPath:" + uploadPath);
                //文件输出目录是否存在,不存在则创建
                File dir = new File(uploadPath);
                if (!dir.exists()) {
                    dir.mkdir();
                }
                //文件名前缀 日期+UUID
                String fileNamePrefix = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + UUID.randomUUID().toString().replace("-", "");
                //文件后缀名
                String fileExtendName = FilenameUtils.getExtension(originalFilename);
                //输出到指定的位置
                String outFileName = fileNamePrefix.concat(".").concat(fileExtendName);
                //文件上传至指定目录
                file.transferTo(new File(dir, outFileName));

            } else {
                //文件名为空,跳出当前循环
                continue;
            }
        }
        return ResultMsg.success();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

jinshengyuanok

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值