Springboot第二篇:与前端fetch通信(关于传输数据上传文件等前后端的处理)

匿名 (未验证) 提交于 2019-12-03 00:34:01

本章讲述的是关于前后端通信关于对应性,前端为react的View,会分传递不同值有不同的处理情况。

首先关于Springboot内的代码变更都是在IndexController.java内,以下是代码:

package maven.example.controller;  import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController;  @RestController @RequestMapping("/index") public class IndexController {      @RequestMapping("/home")     public String home() {         return "Hello World!";     }      }
View Code


1:传递普通类型的数据,如string

前端:

fetch(‘http://localhost:8080/index/name‘, {   method:‘post‘,   headers: {     "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"   },   body:"firstName=zhu&lastName=yitian", }).then(response => response.text()).then(data => {   alert(data) }).catch(function(e){   alert("error:" + e); })    

后台:




@RequestParam:用于访问 Servlet 请求参数。参数值转换为已声明的方法参数类型。


2:传递Json类型的数据,接收方为类

let temp = {}; temp.lastName = ‘yitian‘; temp.firstName = ‘zhu‘;  fetch(‘http://localhost:8080/index/userName‘, {   method:‘post‘,   headers: {     ‘Content-Type‘: ‘application/json‘   },   body:JSON.stringify(temp), }).then(response => response.text()).then(data => {   alert(data) }).catch(function(e){   alert("error:" + e); })

后台:

IndexController.java




User.java

package maven.example.entity;  public class User {      private String lastName;     private String firstName;          public String getLastName(){         return lastName;     }          public void setLastName(String lastName){         this.lastName = lastName;     }          public String getFirstName(){         return firstName;     }          public void setFirstName(String firstName){         this.firstName = firstName;     } }


3:传递Json类型的数据, 接收方为map

前端:

let temp = {}; temp.lastName = ‘yitian‘; temp.firstName = ‘zhu‘;
fetch(
‘http://localhost:8080/index/mapName‘, {   method:‘post‘,   headers: {     ‘Content-Type‘: ‘application/json‘   },   body:JSON.stringify(temp), }).then(response => response.text()).then(data => {   alert(data) }).catch(function(e){   alert("error:" + e); })

后台:

@RequestMapping("mapName") public String getMapName(@RequestBody Map<String, String> map) {
  return map.get("firstName") + map.get("lastName"); }


4. 上传单个文件或图片

前端:

<form>     <input type="file" id="picture" />     <br/>     <button type="button" onClick={this.handleFile}>上传图片</button>   </form>  
handleFile(){   let picture = document.getElementById("picture").files;   let formData = new FormData();   formData.append(‘file‘, picture[0]);    fetch(‘http://localhost:8080/index/getPicture‘, {     method:‘post‘,     body:formData,   }).then(response => response.text()).then(data => {     alert(data)   }).catch(function(e){     alert("error:" + e);   })     }

后台:

    @RequestMapping("getPicture")     public String handleFormUpload(@RequestParam("file") MultipartFile file) {         try{             if (!file.isEmpty()) {                 byte[] bytes = file.getBytes();                 File picture = new File("temp.png");//这里指明上传文件保存的地址                 FileOutputStream fos = new FileOutputStream(picture);                   BufferedOutputStream bos = new BufferedOutputStream(fos);                 bos.write(bytes);                 bos.close();                 fos.close();                 return "success";             }         }catch (IOException e){             System.out.println(e);         }         return "failed";     }


5.上传多个文件或图片

前端:

<form>     <input type="file" id="picture" multiple="multiple"/>     <br/>     <button type="button" onClick={this.handleFile}>上传图片</button>   </form>  
handleFile(){   let picture = document.getElementById("picture").files;   let formData = new FormData();    for (let i = 0; i < picture.length; ++i){     formData.append(‘file‘, picture[i]);   }    fetch(‘http://localhost:8080/index/getPictures‘, {     method:‘post‘,     body:formData,   }).then(response => response.text()).then(data => {     alert(data)   }).catch(function(e){     alert("error:" + e);   })     }

后台:

    @RequestMapping("getPictures")     public String handleFormsUpload(HttpServletRequest request) {         try{             List<MultipartFile>files = ((MultipartHttpServletRequest) request).getFiles("file");                          MultipartFile file = null;                          for(int i = 0; i < files.size(); ++i){                 file = files.get(i);                 if (!file.isEmpty()) {                     byte[] bytes = file.getBytes();                     File picture = new File("temp" + String.valueOf(i) + ".png");//这里指明上传文件保存的地址                     FileOutputStream fos = new FileOutputStream(picture);                       BufferedOutputStream bos = new BufferedOutputStream(fos);                     bos.write(bytes);                     bos.close();                     fos.close();                 }             }                          return "success";                          }catch (IOException e){                 System.out.println(e);             }         return "failed";     }

原文:https://www.cnblogs.com/tianshu/p/9218309.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!