关于前端接口传递的方法,推荐按以下使用:

若要在服务器上创建资源,推荐使用POST方法

若要检索某个资源,推荐使用GET方法

若要更新资源,推荐使用PUT方法

若要删除某个资源,推荐使用DELETE方法


另外本章主要讲述的是关于前后端通信关于对应性,前端为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!";
} }

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);
})

后台:

 @RequestMapping("name")
    public String getName(@RequestParam("firstName") String firstName, @RequestParam("lastName") String lastName) {
        return firstName + lastName;
    }

@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

 @RequestMapping("userName")
    public String getUserName(@RequestBody User user) {
        return user.getFirstName() + user.getLastName();
    }

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]);//这里的file要与后台@RequestParam的参数值相对应   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";
}

Springboot第三篇:与前端fetch通信(关于前端传输json数据上传文件等等前后端的处理)的更多相关文章

  1. 重新想象 Windows 8.1 Store Apps (89) - 通信的新特性: 下载数据, 上传数据, 上传文件

    [源码下载] 重新想象 Windows 8.1 Store Apps (89) - 通信的新特性: 下载数据, 上传数据, 上传文件 作者:webabcd 介绍重新想象 Windows 8.1 Sto ...

  2. 《手把手教你》系列技巧篇(五十四)-java+ selenium自动化测试-上传文件-中篇(详细教程)

    1.简介 在实际工作中,我们进行web自动化的时候,文件上传是很常见的操作,例如上传用户头像,上传身份证信息等.所以宏哥打算按上传文件的分类对其进行一下讲解和分享. 2.为什么selenium没有提供 ...

  3. Springboot第二篇:与前端fetch通信(附springboot解决跨域方法)

    说到与前端通信,明白人都知道这章肯定会写两部分的东西啦. 关于后台 ①首先回顾前文,上一章环境搭建如图: ②我们在maven.example.controller下添加一个文件,并附上如图代码: ③: ...

  4. SpringBoot非官方教程 | 第十七篇:上传文件

    转载请标明出处: 原文首发于:https://www.fangzhipeng.com/springboot/2017/07/11/springboot14-upload/ 本文出自方志朋的博客 这篇文 ...

  5. 第九篇:web之前端之web上传文件的方式

    前端之web上传文件的方式   前端之web上传文件的方式 本节内容 web上传文件方式介绍 form上传文件 原生js实现ajax上传文件 jquery实现ajax上传文件 form+iframe构 ...

  6. fetch上传文件报错的问题(multipart: NextPart: EOF)

    技术栈 后台: gin(golang) 前端: react+antd+dva 问题 前端这边使用fetch发送http请求的时候,后端解析formData报错: multipart: NextPart ...

  7. 基于spring-boot的web应用,ckeditor上传文件图片文件

    说来惭愧,这个应用调试,折腾了我一整天,google了很多帖子,才算整明白,今天在这里做个记录和分享吧,也作为自己后续的参考! 第一步,ckeditor(本博文论及的ckeditor版本4.5.6)的 ...

  8. 三种方式上传文件-Java

    前言:负责,因为该项目他(jetty嵌入式开始SpringMvc)实现文件上传的必要性,并拥有java文件上传这一块还没有被曝光.并 Http 更多晦涩协议.因此,这种渐进的方式来学习和实践上载文件的 ...

  9. java前后分离使用fetch上传文件失败500

    这次不是写什么技术要点,仅仅是记录一下 最近遇到的一个问题 背景 使用fetch向java后台上传文件时,前端调试报错500,后端的报错为multipart 无法解析,翻译过来大概是这个意思. 由于本 ...

随机推荐

  1. Openssl oscp命令

    一.简介 ocsp,在线证书状态命,能够执行很多OCSP的任务,可以被用于打印请求文件和响应文件, 二.语法 openssl ocsp [-out file] [-issuer file] [-cer ...

  2. ethtool -p eth0 物理口一个灯在不停的闪烁

    摘自:https://blog.csdn.net/morigejile/article/details/78598645 你的  服务器有多个网卡并且已经配置好运行当中,你却没记得eth0.eth1. ...

  3. JVM内存模型以及堆分配参数

    程序计数器: 存放下一条要运行的指令:每个线程都必须用一个独立的程序计数器,用于记录下一条要运行的指令.程序计数器是一块线程私有的内存空间. JAVA虚拟机栈: 线程私有的内存空间,它保存方法的局部变 ...

  4. Reactor模式和NIO(转载二)

    本文可看成是对Doug Lea Scalable IO in Java一文的翻译. 当前分布式计算 Web Services盛行天下,这些网络服务的底层都离不开对socket的操作.他们都有一个共同的 ...

  5. Web开发入门经典:使用PHP6、Apache和MySQL 中文pdf扫描版​

    通过学习本书,读者很快就能明白为什么PHP.Apache和MySQL会迅速成为开发动态网站最流行的方式,本书将为读者理解这3个核心组件如何独立工作和协同工作奠定良好的基础,引导读者充分利用它们提供的各 ...

  6. SlidesJS基本使用方法和官方文档解释

    Slides – 是一个简单的,容易定制和风格化,的jQuery幻灯片插件. Slides提供褪色或幻灯片过渡效果,图像淡入淡出,图像预压,自动生成分页,循环,自动播放的自定义等很多选项. 用Slid ...

  7. [C#]C#中字符串的操作

    1.Replace(替换字符):public string Replace(char oldChar,char newChar);在对象中寻找oldChar,如果寻找到,就用newChar将oldCh ...

  8. coderfoces D. Gourmet choice

      D. Gourmet choice time limit per test 2 seconds memory limit per test 256 megabytes   题目链接: https: ...

  9. leetcode 23. 合并K个排序链表 JAVA

    题目: 合并 k 个排序链表,返回合并后的排序链表.请分析和描述算法的复杂度. 示例: 输入: [   1->4->5,   1->3->4,   2->6 ] 输出: ...

  10. ocp题库变化,052新加的考试题及答案整理-32

    32. Examine these commands and their output: • SQL> SELECT * FROM emp; • ENO ENAME • ---- ----- • ...