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

SpringBoot2.x文件上传简单案例

  • Spring Boot文件上传简单案例
    • 1. 创建工程
    • 2. pom.xml文件
    • 2. application.yml
    • 3.前端fileupload.html
    • 4. 后端控制器

Spring Boot文件上传简单案例

本案例环境:

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

1. 创建工程

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

2. pom.xml文件


<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.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.3.0.RELEASEversion>
        <relativePath/> 
    parent>
    <groupId>org.yuangroupId>
    <artifactId>yuan-fileuploadartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <name>yuan-fileuploadname>
    <description>Demo project for Spring Bootdescription>

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

    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-thymeleafartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>org.mybatis.spring.bootgroupId>
            <artifactId>mybatis-spring-boot-starterartifactId>
            <version>2.1.2version>
        dependency>

        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <scope>runtimescope>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-configuration-processorartifactId>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>

        
        <dependency>
            <groupId>commons-fileuploadgroupId>
            <artifactId>commons-fileuploadartifactId>
            <version>1.4version>
        dependency>



        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintagegroupId>
                    <artifactId>junit-vintage-engineartifactId>
                exclusion>
            exclusions>
        dependency>
    dependencies>

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

project>

2. application.yml

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

3.前端fileupload.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;

/**
 * 

* Description: 文件上传简单案例
*

* Author:jinshengyuan
* Datetime: 2020/5/24 14:55 *

* * @since 2020/5/24 14:55 */
@Controller public class FileUploadController { /** *

* Description: 跳转至文件上传页面的handler
*

* Author:jinshengyuan
* Datetime: 2020/5/24 14:56 *

* * @return 跳转的模板名称 * @since 2020/5/24 14:56 */
@RequestMapping("/initUpload") public String initUpload() { return "fileUpload"; } /** *

* Description: 文件上传方法
*

* Author:jinshengyuan
* Datetime: 2020/5/24 14:57 *

* * @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(); } }

你可能感兴趣的:(SpringBoot2.x)