Home > Java > javaTutorial > How to implement SpringBoot file upload function

How to implement SpringBoot file upload function

WBOY
Release: 2023-05-17 12:15:36
forward
1637 people have browsed it

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="images/1.GIF"/ alt="How to implement SpringBoot file upload function" >
<hr/>
<div >
    <h2>注册用户~</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>
Copy after login

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 "注册用户成功/文件上传成功";
    }
}
Copy after login

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 "注册用户成功/文件上传成功";
}
Copy after login

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());
    }
}
Copy after login
@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 "注册用户成功/文件上传成功";
}
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template