ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

SpringBoot之文件上传

2022-02-01 20:03:04  阅读:147  来源: 互联网

标签:info 文件 SpringBoot boot file import org LOGGER 上传


前言

针对thymeleaf对文件上传的方法进行总结,有不到之处敬请指正!

1.pom.xml依赖的编写

 <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-log4j2</artifactId>
            <version>2.6.3</version>
        </dependency>
    </dependencies>

2.application.yml配置文件的编写

# 端口
server:
  port: 8014

spring:
  application:
    # 应用名称
    name: node14-boot-file
  servlet:
    multipart:
      # 启用
      enabled: true
      # 上传文件单个限制
      max-file-size: 5MB
      # 总限制
      max-request-size: 6MB
  thymeleaf:
    cache:
      false  # 开发时关闭缓存,不然没法看到实时页面
    prefix:
      classpath: /templates # 访问template下的html文件需要配置模板,映射

3.templates下上传页面的编写

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<hr/>
<h3>1、单文件上传</h3>
<form method="POST" action="/upload1" enctype="multipart/form-data">
    上传人:<input type="text" name="userName" /><br/>
    文件一:<input type="file" name="file" /><br/>
    <input type="submit" value="Submit" />
</form>
<hr/>
<h3>2、多文件上传</h3>
<form method="POST" action="/upload2" enctype="multipart/form-data">
    上传人:<input type="text" name="userName" /><br/>
    文件一:<input type="file" name="file" /><br/>
    文件二:<input type="file" name="file" /><br/><br/>
    <input type="submit" value="Submit" />
</form>
</body>
</html>
<hr/>

4.文件上传控制器的编写

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Map;

@RestController
public class FileController {

    private static final Logger LOGGER = LoggerFactory.getLogger(FileController.class) ;
    /**
     * 如果单个文件大小超出1MB,抛出异常
     * FileSizeLimitExceededException:
     * The field file exceeds its maximum permitted size of 1048576 bytes.
     */
    @RequestMapping("/upload1")
    public String upload1 (HttpServletRequest request, @RequestParam("file") MultipartFile file){
        Map<String, String[]> paramMap = request.getParameterMap() ;
        if (!paramMap.isEmpty()){
            LOGGER.info("paramMap == >>{}",paramMap);
        }
        try{
            if (!file.isEmpty()){
                // 打印文件基础信息
                LOGGER.info("Name == >>{}",file.getName());
                LOGGER.info("OriginalFilename == >>{}",file.getOriginalFilename());
                LOGGER.info("ContentType == >>{}",file.getContentType());
                LOGGER.info("Size == >>{}",file.getSize());
                // 文件输出地址
                String filePath = "D:\\boot-file\\" ;
                new File(filePath).mkdirs();
                File writeFile = new File(filePath, file.getOriginalFilename());
                file.transferTo(writeFile);
            }
            return "success" ;
        } catch (Exception e){
            e.printStackTrace();
            return "系统异常" ;
        }
    }

    /**
     * 如果上传文件总大小超过6MB,抛出异常
     * SizeLimitExceededException:
     * the request was rejected because its size (9052616) exceeds the configured maximum (6291456)
     */
    @RequestMapping("/upload2")
    public String upload2 (HttpServletRequest request, @RequestParam("file") MultipartFile[] fileList){
        Map<String, String[]> paramMap = request.getParameterMap() ;
        if (!paramMap.isEmpty()){
            LOGGER.info("paramMap == >>{}",paramMap);
        }
        try{
            if (fileList.length > 0){
                for (MultipartFile file:fileList){
                    // 打印文件基础信息
                    LOGGER.info("Name == >>{}",file.getName());
                    LOGGER.info("OriginalFilename == >>{}",file.getOriginalFilename());
                    LOGGER.info("ContentType == >>{}",file.getContentType());
                    LOGGER.info("Size == >>{}",file.getSize());
                    // 文件输出地址
                    String filePath = "D:\\boot-file\\" ;
                    new File(filePath).mkdirs();
                    File writeFile = new File(filePath, file.getOriginalFilename());
                    file.transferTo(writeFile);
                }
            }
            return "success" ;
        } catch (Exception e){
            return "fail" ;
        }
    }

标签:info,文件,SpringBoot,boot,file,import,org,LOGGER,上传
来源: https://www.cnblogs.com/songwp/p/15859502.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有