文件上传

前言

在Web应用系统开发中,文件上传是必不可少的功能

看完本章你将会知道

如何实现异步上传文件,并实现简单地图片回显

配置文件

pom



    4.0.0

    com.boot
    demo-file
    0.0.1-SNAPSHOT
    jar

    demo-file
    Demo project for Spring Boot

    
        org.springframework.boot
        spring-boot-starter-parent
        2.0.6.RELEASE
         
    

    
        UTF-8
        UTF-8
        1.8
    

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

        
            org.projectlombok
            lombok
            true
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
            org.springframework.boot
            spring-boot-starter-freemarker
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    



application.yml

sys:
  basePath: E:\picture\
  webPath: http://localhost:8080/
  imgPath: http://localhost:8080/image/
spring:
  mvc:
    static-path-pattern: /image/**
  resources:
    static-locations:  file:E://picture/

HelloFile

项目架构图

文件上传_第1张图片
image.png

FileController

@Controller
public class FileController {

    @Value("${sys.basePath}")
    private String basePath;
    @Value("${sys.imgPath}")
    private String imgPath;

    /**
     * 实现文件上传
     */
    @RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
    @ResponseBody
    public String upload(MultipartFile file) {
        if (file.isEmpty()) {//判断文件为null
            return ResultEnum.FILEISNULL.getMessage();
        }

        String fileName = file.getOriginalFilename();//获取文件名
        String path = basePath ;   //自定义文件存放位置
        String suffix = fileName.substring(fileName.lastIndexOf("."));//获取文件后缀名
        String newName = UUID.randomUUID().toString()+suffix;
        File dest = new File(path + newName);
        if (!dest.getParentFile().exists()) { //判断文件父目录是否存在
            dest.getParentFile().mkdir();    //创建目录
        }
        try {
            file.transferTo(dest); //保存文件
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return imgPath+newName;
    }
}

PageController

@Controller
public class PageController {

    @RequestMapping("/index")
    public String index(){
        return "index";
    }
}

ResultEnum

@Getter
public enum ResultEnum {
    FILEISNULL(1,"文件为null")
    ,UPLOADSUCCESS(2,"上传成功");

    private Integer code;
    private String message;

    ResultEnum(Integer code, String message) {
        this.code = code;
        this.message = message;
    }
}

DemoFileApplication

@SpringBootApplication
public class DemoFileApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoFileApplication.class, args);
    }
}

index.ftl




    
    Title



图片回显


run

文件上传_第2张图片

你可能感兴趣的:(文件上传)