您当前的位置: 首页 >  spring

梁云亮

暂无认证

  • 2浏览

    0关注

    1211博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

SpringBoot 文件上传

梁云亮 发布时间:2020-06-11 10:16:55 ,浏览量:2

创建SpringBoot项目 Maven依赖

    org.springframework.boot
    spring-boot-starter-web


    org.springframework.boot
    spring-boot-starter-thymeleaf


    com.fasterxml.jackson.core
    jackson-databind

application.yml
spring:
  #前缀,也就是模板存放的路径
  thymeleaf:
    prefix: classpath:/templates/
    #编码格式
    encoding: UTF-8
    #关闭缓存,不然无法看到实时页面
    cache: false
    #后缀
    suffix: .html
    #设置不严格的html
    mode: HTML
    servlet:
      content-type: text/html
单文件上传 前台页面


    
        
        Insert title here
    
    
        文件上传
        
            选择文件: 
            
        
    

后台Controller
@Controller
public class FileUploadController {
    /**
     * 实现单文件上传
     */
    @PostMapping("/fileUpload")
    @ResponseBody
    public String fileUpload(@RequestParam("fileName") MultipartFile file) {
        if (file.isEmpty()) {
            return "false";
        }
        String fileName = file.getOriginalFilename();
        int size = (int) file.getSize();
        System.out.println(fileName + "-->" + size);

        String path = "E:/test";
        File dest = new File(path + "/" + fileName);
        if (!dest.getParentFile().exists()) { //判断文件父目录是否存在
            dest.getParentFile().mkdir();
        }
        try {
            file.transferTo(dest); //保存文件
            return "true";
        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
            return "false";
        }
    }
}
多文件上传 前台页面


    
        
        Insert title here
    
    
        文件上传
        
            选择文件1: 
            选择文件2: 
            选择文件3: 
            
        
    

后台Controller
@Controller
public class FileUploadController {
    /**
     * 实现多文件上传
     */
    @PostMapping(value = "/multifileUpload")
    @ResponseBody
    public String multifileUpload(HttpServletRequest request) {
        List files = ((MultipartHttpServletRequest) request).getFiles("fileName");

        if (files.isEmpty()) {
            return "false";
        }

        String path = "E:/test";

        for (MultipartFile file : files) {
            String fileName = file.getOriginalFilename();
            int size = (int) file.getSize();
            System.out.println(fileName + "-->" + size);

            if (file.isEmpty()) {
                return "false";
            }
            File dest = new File(path + "/" + fileName);
            if (!dest.getParentFile().exists()) { //判断文件父目录是否存在
                dest.getParentFile().mkdir();
            }
            try {
                file.transferTo(dest);
            } catch (Exception e) {
                e.printStackTrace();
                return "false";
            }
        }
        return "true";
    }
}
关注
打赏
1665409997
查看更多评论
立即登录/注册

微信扫码登录

0.0674s