当前位置:网站首页>16. File upload

16. File upload

2022-08-10 23:49:00 If you want to learn, learn Big Wolf


16.1 应用实例

16.1.1 需求说明

  • 演示 Spring-Boot Register users through the form,And support uploading pictures
  • 回顾 SpringMVC 文件上传 ==> 文章链接

16.1.2 代码实现

  1. 创建 templates/upload.html,Only one avatar is required,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"/>
<hr/>
<div style="text-align: center">
    <h1>注册用户~</h1>
    <form action="#" method="post" th:action="@{/upload}" enctype="multipart/form-data">
        用户名:<input type="text" style="width:150px" name="name"/><br/><br/>
        电 邮:<input type="text" style="width:150px" name="email"/><br/><br/>
        年 龄:<input type="text" style="width:150px" name="age"/><br/><br/>
        职 位:<input type="text" style="width:150px" name="job"/><br/><br/>
        头 像:<input type="file" style="width:150px" name="header"><br/><br/>
        宠 物:<input type="file" style="width:150px" name="photos" multiple><br/><br/>
        <input type="submit" value="注册"/>
        <input type="reset" value="重新填写"/>
    </form>
</div>
<hr/>
<!--<img src="images/logo.png"/>-->
</body>
</html>
  1. 创建 D:\xjs_springboot\springboot-usersys\src\main\java\com\xjs\springboot\controller\UploadController.java
package com.xjs.springboot.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/** * @Author: 谢家升 * @Version: 1.0 */
@Controller
@Slf4j
public class UploadController {
    

    //Processing is forwarded to user registration-Complete the file upload page
    @GetMapping("/upload.html")
    public String uploadPage() {
    
        return "upload"; //thymeleaf 视图解析,转发到 templates/upload.html
    }

    //处理用户的注册请求-Including handling file uploads
    @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 {
    

        //Output the obtained information
        log.info("上传的信息 name={} email={} age={} job={} header={} photos={}",
                name, email, age, job, header.getSize(), photos.length);

        //We save the file to the specified directory,比如 D:\\temp_upload
        //1. Save the file to the specified directory first 比如 D:\\temp_upload
        if (!header.isEmpty()) {
     //处理头像
            //Get the original filename of the uploaded file
            String originalFilename = header.getOriginalFilename();
            header.transferTo(new File("D:\\temp_upload\\" + originalFilename));
        }

        //Process pet pictures
        if (photos.length > 0) {
    
            for (MultipartFile photo : photos) {
     //遍历
                if (!photo.isEmpty()) {
    
                    String originalFilename = photo.getOriginalFilename();
                    photo.transferTo(new File("D:\\temp_upload\\" + originalFilename));
                }
            }
        }

        //==============================================

        //2. I'll demonstrate saving the file to a dynamically created directory later
        // 比如:类路径下的
        //(1) Get the classpath first(运行的时候)
        String path = ResourceUtils.getURL("classpath:").getPath();
        //log.info("path={}", path);

        //(2)Dynamically create the specified directory
        File file = new File(path + "static/images/upload/");
        if (!file.exists()) {
    //如果目录不存在 就创建
            file.mkdirs();
        }

        //处理头像
        if (!header.isEmpty()) {
    
            String originalFilename = header.getOriginalFilename();
            //Here you need to specify the absolute path to save the file,即:
            //log.info("保存文件的绝对路径={}", file.getAbsolutePath());
            // The output can see whether it needs to be added when the path is spliced "/"
            //Save to a dynamically created directory
            header.transferTo(new File(file.getAbsoluteFile() + "/" + originalFilename));
        }

        //Process pet pictures
        if (photos.length > 0) {
    
            for (MultipartFile photo : photos) {
    
                String originalFilename = photo.getOriginalFilename();
                //Save to a dynamically created directory
                photo.transferTo(new File(file.getAbsoluteFile() + "/" + originalFilename));
            }
        }

        return "注册用户成功/文件上传成功";
    }

}

在这里插入图片描述

  1. 修改 WebConfig 配置,放行/upload.html 和 /upload 请求
package com.xjs.springboot.config;

import com.xjs.springboot.interceptor.LoginInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/** * @Author: 谢家升 * @Version: 1.0 */
@Configuration
public class WebConfig /*implements WebMvcConfigurer*/ {
    

    //@Override
    //public void addInterceptors(InterceptorRegistry registry) {
    
    //
    // //注册自定义拦截器LoginInterceptor
    // registry.addInterceptor(new LoginInterceptor())
    // .addPathPatterns("/**") //这里拦截所有的请求
    // .excludePathPatterns("/","/login","/images/**"); //Specifies which to release,Add release request paths according to business needs
    //
    //}

    @Bean
    public WebMvcConfigurer webMvcConfigurer() {
    

        return new WebMvcConfigurer() {
    
            @Override
            public void addInterceptors(InterceptorRegistry registry) {
    
                //注册拦截器
                registry.addInterceptor(new LoginInterceptor())
                        .addPathPatterns("/**")
                        .excludePathPatterns("/", "/login", "/images/**", "/upload.html", "/upload");
            }
        };
    }

}

  1. Modify the parameters of file upload according to project requirements,Otherwise the file upload will throw an exception

在这里插入图片描述

  1. 创建 resources\application.yml Modify file upload configuration parameters

    max-file-size 单个文件大小
    max-request-size 一次请求最大上传大小 (多个文件)

spring:
  servlet:
    multipart:
      max-file-size: 10MB # Indicates the maximum upload of a single file 10MB
      max-request-size: 50MB # Indicates that multiple files can be uploaded at most in one request 10MB

16.1.3 Complete registered user/上传图片 -测试

16.1.3.1 启动项目

16.1.3.2 浏览器:http://localhost:8080/upload.html

16.1.3.3 页面效果

在这里插入图片描述

16.1.4 课后作业-扩展要求

  1. Fix file overwrite issue,如果文件名相同,There will be coverage issues,如何解决?
  2. Solve the problem of file sub-directory storage,如果将文件都上传到一个目录下,当上传文件很多时,会造成访问文件速度变慢,因此 可以将文件上传到不同目录 比如 一天上传的文件,Put them together in one folder 年/月/日,比如 2022/11/11 目录
  3. Refer to the previous study java web ==> 文章链接

16.1.5 homework answers

  1. Generate a uniquely identified file name
String fileName = UUID.randomUUID().toString()+"_"+System.currentTimeMillis()+"_" +originalFilename;
  • 修改 UploadController.java
package com.xjs.springboot.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/** * @Author: 谢家升 * @Version: 1.0 */
@Controller
@Slf4j
public class UploadController {
    

    //Processing is forwarded to user registration-Complete the file upload page
    @GetMapping("/upload.html")
    public String uploadPage() {
    
        return "upload"; //thymeleaf 视图解析,转发到 templates/upload.html
    }

    //处理用户的注册请求-Including handling file uploads
    @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 {
    

        //Output the obtained information
        log.info("上传的信息 name={} email={} age={} job={} header={} photos={}",
                name, email, age, job, header.getSize(), photos.length);

        //We save the file to the specified directory,比如 D:\\temp_upload
        //1. Save the file to the specified directory first 比如 D:\\temp_upload
        //if (!header.isEmpty()) { //处理头像
        // //Get the original filename of the uploaded file
        // String originalFilename = header.getOriginalFilename();
        // header.transferTo(new File("D:\\temp_upload\\" + originalFilename));
        //}

        //Process pet pictures
        //if (photos.length > 0) {
    
        // for (MultipartFile photo : photos) { //遍历
        // if (!photo.isEmpty()) {
    
        // String originalFilename = photo.getOriginalFilename();
        // photo.transferTo(new File("D:\\temp_upload\\" + originalFilename));
        // }
        // }
        //}

        //==============================================

        //2. I'll demonstrate saving the file to a dynamically created directory later
        // 比如:类路径下的
        //(1) Get the classpath first(运行的时候)
        String path = ResourceUtils.getURL("classpath:").getPath();
        //log.info("path={}", path);

        //(2)Dynamically create the specified directory
        File file = new File(path + "static/images/upload/");
        if (!file.exists()) {
    //如果目录不存在 就创建
            file.mkdirs();
        }

        //处理头像
        if (!header.isEmpty()) {
    
            String originalFilename = header.getOriginalFilename();
            String fileName = UUID.randomUUID().toString()+"_"+System.currentTimeMillis()+"_" +originalFilename;
            //Here you need to specify the absolute path to save the file,即:
            //log.info("保存文件的绝对路径={}", file.getAbsolutePath());
            // The output can see whether it needs to be added when the path is spliced "/"
            //Save to a dynamically created directory
            //header.transferTo(new File(file.getAbsoluteFile() + "/" + originalFilename));
            header.transferTo(new File(file.getAbsoluteFile() + "/" + fileName));
        }

        //Process pet pictures
        if (photos.length > 0) {
    
            for (MultipartFile photo : photos) {
    
                String originalFilename = photo.getOriginalFilename();
                String fileName = UUID.randomUUID().toString()+"_"+System.currentTimeMillis()+"_" +originalFilename;
                //Save to a dynamically created directory
                //photo.transferTo(new File(file.getAbsoluteFile() + "/" + originalFilename));
                photo.transferTo(new File(file.getAbsoluteFile() + "/" + fileName));
            }
        }

        return "注册用户成功/文件上传成功";
    }

}

  1. 编写一个工具类,The corresponding directory can be generated according to the current date
  • 编写工具类 WebUtils.java
package com.xjs.springboot.utils;


import java.text.SimpleDateFormat;
import java.util.Date;

/** * @Author: 谢家升 * @Version: 1.0 */
public class WebUtils {
    

    //Define a file upload path
    public static String UPLOAD_FILE_DIRECTORY = "static/images/upload/";

    //编写方法, Generate a directory based on the current date 年/月/日
    public static String getUploadFileDirectory() {
    
        return UPLOAD_FILE_DIRECTORY + new SimpleDateFormat("yyyy/MM/dd").format(new Date());
    }

    //测试
    public static void main(String[] args) {
    

        System.out.println(WebUtils.getUploadFileDirectory());
    }

}

  • 修改 UploadController.java

在这里插入图片描述

package com.xjs.springboot.controller;

import com.xjs.springboot.utils.WebUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/** * @Author: 谢家升 * @Version: 1.0 */
@Controller
@Slf4j
public class UploadController {
    

    //Processing is forwarded to user registration-Complete the file upload page
    @GetMapping("/upload.html")
    public String uploadPage() {
    
        return "upload"; //thymeleaf 视图解析,转发到 templates/upload.html
    }

    //处理用户的注册请求-Including handling file uploads
    @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 {
    

        //Output the obtained information
        log.info("上传的信息 name={} email={} age={} job={} header={} photos={}",
                name, email, age, job, header.getSize(), photos.length);

        //We save the file to the specified directory,比如 D:\\temp_upload
        //1. Save the file to the specified directory first 比如 D:\\temp_upload
        //if (!header.isEmpty()) { //处理头像
        // //Get the original filename of the uploaded file
        // String originalFilename = header.getOriginalFilename();
        // header.transferTo(new File("D:\\temp_upload\\" + originalFilename));
        //}

        //Process pet pictures
        //if (photos.length > 0) {
    
        // for (MultipartFile photo : photos) { //遍历
        // if (!photo.isEmpty()) {
    
        // String originalFilename = photo.getOriginalFilename();
        // photo.transferTo(new File("D:\\temp_upload\\" + originalFilename));
        // }
        // }
        //}

        //==============================================

        //2. I'll demonstrate saving the file to a dynamically created directory later
        // 比如:类路径下的
        //(1) Get the classpath first(运行的时候)
        String path = ResourceUtils.getURL("classpath:").getPath();
        //log.info("path={}", path);

        //(2)Dynamically create the specified directory
        File file = new File(path + WebUtils.getUploadFileDirectory());
        if (!file.exists()) {
    //如果目录不存在 就创建
            file.mkdirs();
        }

        //处理头像
        if (!header.isEmpty()) {
    
            String originalFilename = header.getOriginalFilename();
            String fileName = UUID.randomUUID().toString()+"_"+System.currentTimeMillis()+"_" +originalFilename;
            //Here you need to specify the absolute path to save the file,即:
            //log.info("保存文件的绝对路径={}", file.getAbsolutePath());
            // The output can see whether it needs to be added when the path is spliced "/"
            //Save to a dynamically created directory
            //header.transferTo(new File(file.getAbsoluteFile() + "/" + originalFilename));
            header.transferTo(new File(file.getAbsoluteFile() + "/" + fileName));
        }

        //Process pet pictures
        if (photos.length > 0) {
    
            for (MultipartFile photo : photos) {
    
                String originalFilename = photo.getOriginalFilename();
                String fileName = UUID.randomUUID().toString()+"_"+System.currentTimeMillis()+"_" +originalFilename;
                //Save to a dynamically created directory
                //photo.transferTo(new File(file.getAbsoluteFile() + "/" + originalFilename));
                photo.transferTo(new File(file.getAbsoluteFile() + "/" + fileName));
            }
        }

        return "注册用户成功/文件上传成功";
    }

}

在这里插入图片描述

原网站

版权声明
本文为[If you want to learn, learn Big Wolf]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/222/202208102335002517.html