search
HomeJavajavaTutorialHow to implement SpringBoot file upload function

1. Application example

Requirements: Demonstrate Spring-Boot to register users through forms and support uploading pictures

2. Code implementation

Code implementation-file upload

Please create templates/upload.html, ensure that only one avatar can be selected, and pets can upload multiple pictures

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>upload</title>
</head>
<body bgcolor="#CED3FE">
<img  src="/static/imghwm/default1.png"  data-src="images/1.GIF"  class="lazy"  / alt="How to implement SpringBoot file upload function" >
<hr/>
<div >
    <h2 id="注册用户">注册用户~</h2>
    <form action="#" th:action="@{/upload}" method="post" enctype="multipart/form-data">
        用户名:<input type="text"  name="name"/><br/><br/>
        电 邮:<input type="text"  name="email"/><br/><br/>
        年 龄:<input type="text"  name="age"/><br/><br/>
        职 位:<input type="text"  name="job"/><br/><br/>
        头 像:<input type="file"  name="header"><br/><br/>
        宠 物:<input type="file"  name="photos" multiple><br/><br/>
        <input type="submit" value="注册"/>
        <input type="reset" value="重新填写"/>
    </form>
</div>
<hr/>
</body>
</html>

2. Create src\main\java\com\llp\springboot\controller \UploadController.java

@Slf4j
@Controller
public class UploadController {
    //处理转发到用户注册-可以完成文件上传页面
    @GetMapping("/upload.html")
    public String uploadPage() {
        return "upload";// 视图解析,转发到templates/upload.html
    }
    @PostMapping("/upload")
    @ResponseBody
    public String upload(@RequestParam("name") String name,
                         @RequestParam("email") String email,
                         @RequestParam("age") Integer age,
                         @RequestParam("job") String job,
                         @RequestParam("header") MultipartFile header,
                         @RequestParam("photos") MultipartFile[] photos) throws IOException {
        log.info("name:{},email:{},age:{},job:{},header.size:{},photos.length:{}",name,email,age,job,header.getSize(),photos.length);
        //1.获取源文件名称
        String originalFilename = header.getOriginalFilename();
        // /E:/IdeaProjects/springboot-sysuser/target/classes/
        String path = ResourceUtils.getURL("classpath:").getPath();
        System.out.println(path);
        File file = new File(path+"static/images/upload/");
        if(!file.exists()){
            file.mkdirs();
        }
        header.transferTo(new File(path+"static/images/upload/"+originalFilename));
        return "注册用户成功/文件上传成功";
    }
}

How to implement SpringBoot file upload function

How to implement SpringBoot file upload function

##3. Lead to two questions

1. File overwriting problem

In the above example, file upload is implemented, but when two different files have the same file name, there will be a file overwriting problem. How to solve it?

@PostMapping("/upload")
@ResponseBody
public String upload(@RequestParam("name") String name,
                     @RequestParam("email") String email,
                     @RequestParam("age") Integer age,
                     @RequestParam("job") String job,
                     @RequestParam("header") MultipartFile header,
                     @RequestParam("photos") MultipartFile[] photos) throws IOException {
    log.info("name:{},email:{},age:{},job:{},header.size:{},photos.length:{}",name,email,age,job,header.getSize(),photos.length);
    //1.获取源文件名称
    String originalFilename = header.getOriginalFilename();
    originalFilename = UUID.randomUUID().toString().replaceAll("-","")+System.nanoTime()+originalFilename;
    //2.获取文件上传的路径
    // /E:/IdeaProjects/springboot-sysuser/target/classes/
    String path = ResourceUtils.getURL("classpath:").getPath();
    System.out.println(path);
    //3.动态的创建文件上传目录
    File file = new File(path+"static/images/upload/");
    if(!file.exists()){
        file.mkdirs();
    }
    //4.将文件传输到目标目录
    header.transferTo(new File(path+"static/images/upload/"+originalFilename));
    return "注册用户成功/文件上传成功";
}

originalFilename = UUID.randomUUID().toString().replaceAll("-","") System.nanoTime() originalFilename;, the implementation idea is to re-upload the file Specify a unique file name

How to implement SpringBoot file upload function

2. Upload all files to one directory. When uploading a lot of files, accessing the files will slow down

Solution: Upload files to different directories. For example, files uploaded on one day should be put into one folder year/month/day, such as 2022/11/11 directory

public class WebUtils {
    //定义一个文件上传的路径
    public static String  UPLOAD_FILE_DIRECTORY = "static/images/upload/";
    //编写方法,生成一个目录-根据当前日期 年/月/日
    public static String getUploadFileDirectory() {
        return UPLOAD_FILE_DIRECTORY + new SimpleDateFormat("yyyy/MM/dd").format(new Date());
    }
}
@PostMapping("/upload")
@ResponseBody
public String upload(@RequestParam("name") String name,
                     @RequestParam("email") String email,
                     @RequestParam("age") Integer age,
                     @RequestParam("job") String job,
                     @RequestParam("header") MultipartFile header,
                     @RequestParam("photos") MultipartFile[] photos) throws IOException {
    //输出获取到的信息
    log.info("上传的信息 name={} email={} age={} job={} header={} photos={} ",
            name, email, age, job, header.getSize(), photos.length);
    //得到类路径(运行的时候)
    String path = ResourceUtils.getURL("classpath:").getPath();
    //log.info("path={}", path);
    //动态创建指定目录
    File file = new File(path + WebUtils.getUploadFileDirectory());
    if (!file.exists()) {//如果目录不存在,我们就创建, 在java io
        file.mkdirs();
    }
    if (!header.isEmpty()) {//处理头像
        //获取上传文件的名字
        String originalFilename = header.getOriginalFilename();
        String fileName = UUID.randomUUID().toString() + "_" + System.currentTimeMillis() + "_" + originalFilename;
        //保存到动态创建的目录
        header.transferTo(new File(file.getAbsolutePath() + "/" + fileName));
    }
    //处理多个文件
    if (photos.length > 0) {
        for (MultipartFile photo : photos) {//遍历
            if (!photo.isEmpty()) {
                String originalFilename = photo.getOriginalFilename();
                String fileName = UUID.randomUUID().toString() + "_" + System.currentTimeMillis() + "_" + originalFilename;
                //保存到动态创建的目录
                photo.transferTo(new File(file.getAbsolutePath() + "/" + fileName));
            }
        }
    }
    return "注册用户成功/文件上传成功";
}

How to implement SpringBoot file upload function

The above is the detailed content of How to implement SpringBoot file upload function. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
JVM performance vs other languagesJVM performance vs other languagesMay 14, 2025 am 12:16 AM

JVM'sperformanceiscompetitivewithotherruntimes,offeringabalanceofspeed,safety,andproductivity.1)JVMusesJITcompilationfordynamicoptimizations.2)C offersnativeperformancebutlacksJVM'ssafetyfeatures.3)Pythonisslowerbuteasiertouse.4)JavaScript'sJITisles

Java Platform Independence: Examples of useJava Platform Independence: Examples of useMay 14, 2025 am 12:14 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunonanyplatformwithaJVM.1)Codeiscompiledintobytecode,notmachine-specificcode.2)BytecodeisinterpretedbytheJVM,enablingcross-platformexecution.3)Developersshouldtestacross

JVM Architecture: A Deep Dive into the Java Virtual MachineJVM Architecture: A Deep Dive into the Java Virtual MachineMay 14, 2025 am 12:12 AM

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVM: Is JVM related to the OS?JVM: Is JVM related to the OS?May 14, 2025 am 12:11 AM

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceJava: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceMay 14, 2025 am 12:05 AM

Java implementation "write once, run everywhere" is compiled into bytecode and run on a Java virtual machine (JVM). 1) Write Java code and compile it into bytecode. 2) Bytecode runs on any platform with JVM installed. 3) Use Java native interface (JNI) to handle platform-specific functions. Despite challenges such as JVM consistency and the use of platform-specific libraries, WORA greatly improves development efficiency and deployment flexibility.

Java Platform Independence: Compatibility with different OSJava Platform Independence: Compatibility with different OSMay 13, 2025 am 12:11 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

What features make java still powerfulWhat features make java still powerfulMay 13, 2025 am 12:05 AM

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

Top Java Features: A Comprehensive Guide for DevelopersTop Java Features: A Comprehensive Guide for DevelopersMay 13, 2025 am 12:04 AM

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool