0
点赞
收藏
分享

微信扫一扫

springboot 上传文件


1、html代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="uploadFile" value="请选择文件" multiple>
    <input type="submit" value="上传">
</form>
</body>
</html>

 

2、上传接口:

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
public class FileController {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");

    @PostMapping("/uploadFile")
    public String uploadFile(MultipartFile uploadFile, HttpServletRequest req) {
        //效验文件大小
        boolean m = FileUtil.checkFileSize(uploadFile, 1, "M");
        if(!m){
            return "上传失败,文件最大只能1M";
        }
        //效验文件类型
        List<String> suffixList = new ArrayList<>();
        suffixList.add("jpg");
        suffixList.add("Png");
        FileUtil.checkFileType(uploadFile,suffixList);

        //获取uploadFile文件在该项目的绝对路径
        String realPath = req.getSession().getServletContext().getRealPath("/uploadFile/"); //定义文件上传的路径
        System.out.println("realPath:" + realPath);
        String format = sdf.format(new Date());
        File folder = new File(realPath + format);
        System.out.println("folder:" + folder);
        //若果不存在该文件夹,则新建
        if (!folder.isDirectory()) {
            folder.mkdirs();
        }
        String oldName = uploadFile.getOriginalFilename();
        String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."), oldName.length());
        try {
            uploadFile.transferTo(new File(folder, newName));
            System.out.println("保存文件成功");
            String filePath = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + "/uploadFile/"
                    + format + newName;
            return filePath;
        } catch (IOException e) {
            // e.printStackTrace();
        }
        return "上传失败!";
    }

}

 

3、设置上传文件的大小配置:

需要设置以下两个参数,不同的版本对应不同的键值,需对应版本

Spring Boot 1.3.x或者之前

multipart.maxFileSize=100Mb
multipart.maxRequestSize=1000Mb

Spring Boot 1.4.x

spring.http.multipart.maxFileSize=100Mb
spring.http.multipart.maxRequestSize=1000Mb

  很多人设置了multipart.maxFileSize但是不起作用,是因为1.4版本以上的配置改了,详见官方文档:spring boot 1.4

 

Spring Boot 2.0之后

spring.servlet.multipart.max-file-size=100MB
spring.servlet.multipart.max-request-size=1000MB

 

 

4、在接口中 可以对文件 进行单独的文件大小和类型判断:

import org.springframework.web.multipart.MultipartFile;

import java.util.Collection;

/**
 * 效验文件
 */
public class FileUtil {

    /**
     * 判断文件大小
     *
     * @param uploadFile 文件对象
     * @param size       大小
     * @param unit       大小单位 B,K,M ,G
     * @return
     */
    public static boolean checkFileSize(MultipartFile uploadFile, int size, String unit) {
//        long len = file.length();
        long len = uploadFile.getSize();
        double fileSize = 0;
        if ("B".equals(unit.toUpperCase())) {
            fileSize = (double) len;
        } else if ("K".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1024;
        } else if ("M".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1048576;
        } else if ("G".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1073741824;
        }
        if (fileSize > size) {
            return false;
        }
        return true;
    }

    /**
     * 判断文件类型
     *
     * @param uploadFile 文件对象
     * @param suffixList 比对的后缀集合[jpg,PNg]
     * @return
     */
    public static boolean checkFileType(MultipartFile uploadFile, Collection suffixList) {
        String originalFilename = uploadFile.getOriginalFilename(); //获取原始文件名
        String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        for (Object o : suffixList) {
            if (o.toString().equalsIgnoreCase(suffix)) {
                return true;
            }
        }
        return false;
    }
}

上面代码 使用方法:

springboot 上传文件_java

 

 

5、项目基本结构:

springboot 上传文件_文件上传_02

 

 

 

 

 

 

 

 

 

 

 

 

举报

相关推荐

0 条评论