栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot+angular 前后端传值交互(含文件上传)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot+angular 前后端传值交互(含文件上传)

开发环境:

Angular 12
springboot 2.2.12.RELEASE

前端变量定义声明
  preUrl: string = 'http://127.0.0.1:8080/user';
  user: any = { username: '伶念', age: 6, classname: 'Class One' };
后台entity代码:
@Data
public class User {

    private String username;

    private String classname;

    private int age;

    private MultipartFile[] files;

}
一 、Get方式传值 1.Path传值

将参数放到路径的一种传值方式,形式类似 user/userInfo/6
前端代码:

  getPath() {
    const { username, age } = this.user;
    this.http.get(`${this.preUrl}/${username}/${age}`).subscribe((res) => {
      console.log(res);
    });
  }

后台 controller 使用@PathVariable 注解 代码:

    @GetMapping("/{username}/{age}")
    public Result getPath(@PathVariable int age, @PathVariable String username) {
        log.info("接收到的信息:用户名:{},年龄:{}", username, age);
        return Result.message("success");
    }
2.Params传值

将参数拼接到地址后面,生成形如 user/userInfo?id=6 的地址
前端代码:

  getQuery() {
    this.http
      .get(`${this.preUrl}/getQuery`, { params: this.user })
      .subscribe((res) => {
        console.log(res);
      });
  }

后台 controller 使用@RequestParam 注解 或者 不使用注解 代码:
(不使用注解时,要保证字段名一致)

    @GetMapping("/getQuery")
    public Result getQuery(@RequestParam("age") int age, String username) {
        log.info("接收到的信息:用户名:{},年龄:{}", username, age);
        return Result.message("success");
    }
二、Post方式传值 1.JSON传值

最常用的一种post传值方式
前端代码:

  jsonPostBody() {
    this.http.post(`${this.preUrl}/postUserInfo`, this.user).subscribe((res) => {
        console.log(res);
      });
  }

后台使用 @RequestBody 注解

    @PostMapping("/postUserInfo")
    public Result postUserInfo(@RequestBody User user) {
        String username = user.getUsername();
        int age = user.getAge();
        log.info("接收到的信息:用户名:{},年龄:{}", username, age);
        return Result.message("success");
    }
2.Form传值

前端代码:

 formPostBody() {
    const form = new FormData();
    for (let key of Object.keys(this.user)) {
      form.append(key, this.user[key]);
    }
    this.http.post(`${this.preUrl}/postFormUserInfo`, form).subscribe((res) => {
      console.log(res);
    });
  }

后台代码:

    @PostMapping("/postFormUserInfo")
    public Result postFormUserModel(User user) {
        log.info("接收到的信息:用户名:{},年龄:{}", user.getUsername(), user.getAge());
        for (MultipartFile file : user.getFiles()) {
            System.out.println(file.getOriginalFilename());
        }
        return Result.message("success");
    }

或者 使用@RequestParam 注解

    @PostMapping("/postFormUserInfo")
    public Result postFormUserInfo(@RequestParam("username") String username, int age) {
        log.info("接收到的信息:用户名:{},年龄:{}", username, age);
        return Result.message("success");
    }

*另:

1.Get的传值方式同样适用于Post,但注意前端Post方法的Body为必填
2.Params传值和Forms传值 在使用Post传值时 后台代码其实是可以用一样的

3.带文件上传的Post传值

前端代码:

  postFormUserModel() {
    const form = new FormData();
    for (let key of Object.keys(this.user)) {
      form.append(key, this.user[key]);
    }
    for (let file of this.files) {
      form.append('files', file);
    }

    this.http.post(`${this.preUrl}/postFormUserModel`, form, {
        // headers: {
        //   enctype: 'multipart/form-data',
        // },
      }).subscribe((res) => {
        console.log(res);
      });
  }

后台代码

    @PostMapping("/postFormUserModel")
    public Result postFormUserModel(User user) {
        log.info("接收到的信息:用户名:{},年龄:{}", user.getUsername(), user.getAge());
        for (MultipartFile file : user.getFiles()) {
            System.out.println(file.getOriginalFilename());
        }
        return Result.message("success");
    }

或者

    @PostMapping("/postFormUserModel")
    public Result postFormUserModel(String username, int age, MultipartFile[] files) {
        log.info("接收到的信息:用户名:{},年龄:{}", username, age);
        for (MultipartFile file : files) {
            System.out.println(file.getOriginalFilename());
        }
        return Result.message("success");
    }

仓库地址:https://gitee.com/zechen21/demo-pass-value.git

参考文章地址:https://blog.csdn.net/u010775025/article/details/80198291

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/463059.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号