基于Springboot实现前端文件上传,后端实现文件存储

1、环境

maven坐标


<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>com.guogroupId>
<artifactId>aliasartifactId>
<version>0.0.1-SNAPSHOTversion>
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.7.10version>
<relativePath/> 
parent>
<name>aliasname>
<description>aliasdescription>
<properties>
<java.version>8java.version>
properties>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>com.mysqlgroupId>
<artifactId>mysql-connector-jartifactId>
<scope>runtimescope>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
案例⼀、实现前端上传,后端给出存储位置。
前端代码:

<dependency>
<groupId>org.mybatis.spring.bootgroupId>
<artifactId>mybatis-spring-boot-starterartifactId>
<version>2.2.2version>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
exclude>
excludes>
configuration>
plugin>
plugins>
build>
project>

2、前端代码

DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="upFileName"><br>
<input type="submit" value="提交">
form>
body>
html>

3、后端代码

响应类

@AllArgsConstructor
@NoArgsConstructor
@Data
public class Result {
    private Integer code;//响应码,1 代表成功; 0 代表失败
    private String msg; //响应信息 描述字符串
    private Object data; //返回的数据

    public static Result success() {
        return new Result(1, "success", null);
    }

    //查询 成功响应
    public static Result success(Object data) {
        return new Result(1, "success", data);
    }

    //失败响应
    public static Result error(String msg) {
        return new Result(0, msg, null);
    }
}

控制类

@Slf4j
@RestController
public class UpLoadController {
    @PostMapping("/upload")
    public Result upload(@RequestParam("upFileName") MultipartFile file) throws
            Exception {
        log.info("upFileName:{}", file);
        String originalFilename = file.getOriginalFilename();
        file.transferTo(new
                File("/Users/guo/IdeaProjects/MyProject/repo/" + originalFilename));
        return Result.success();
    }
}

你可能感兴趣的:(spring,boot,前端,java)