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

本章讲述的是关于前后端通信关于对应性,前端为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]);

  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

时间: 2024-08-01 08:58:06

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

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

这次不是写什么技术要点,仅仅是记录一下 最近遇到的一个问题 背景 使用fetch向java后台上传文件时,前端调试报错500,后端的报错为multipart 无法解析,翻译过来大概是这个意思. 由于本人不会java所以这里只是记录一下前端的注意事项. 原因 问题的主要原因在于,我在上传时设置了contenttype,这里就不得不提一下,fetch中由于之前使用的时候如果我不设置contenttype那么我向后端传送json时就会报错. 因为contenttype本来就是用于设置http的格式的,

图片上传并回显后端篇

图片上传并回显后端篇 我们先看一下效果 继上一篇的图片上传和回显,我们来实战一下图片上传的整个过程,今天我们将打通前后端,我们来真实的了解一下,我们上传的文件,是以什么样的形式上传到服务器,难道也是一张图片?等下我们来揭晓 我们在实战开始前呢,我们先做一下准备工作,比如新建一个java web工程,如果你不懂这个的话,那我建议你先学一下Javaweb,可以去我的公众号找一下这方面的教程.我们就给我们的工程起名为UpImg,我们再给他建一个web包和util包,再把我们以前前端做的图片回显的代码拷

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

说来惭愧,这个应用调试,折腾了我一整天,google了很多帖子,才算整明白,今天在这里做个记录和分享吧,也作为自己后续的参考! 第一步,ckeditor(本博文论及的ckeditor版本4.5.6)的配置图片文件上传功能,默认这个是没有开启的,就不用多说,ckeditor官网上也说的很清楚!http://docs.ckeditor.com 下面简单的说下配置(配置文件algoConfig.js): 1 CKEDITOR.editorConfig = function( config ) { 2

前端PHP入门-031-文件上传-六脉神剑

php.ini的设置 php.ini的文件太多,找不到的时候你可以使用 Ctrl+F 搜索相关配置项. 配置项 功能说明 file_uploads on 为开启文件上传功能,off 为关闭 post_max_size 系统允许的POST传参的最大值 upload_max_filesize 系统允许的上传文件的最大值 memory_limit 内存使用限制 建议设置: file_size(文件大小) < upload_max_filesize < post_max_size < memor

前端上传文件的方法总结

最近做了阿里云的oss上传,顺便来总结下上传文件的几种主要方法. 第一种:经典的form和input上传. 设置form的aciton为后端页面,enctype="multipart/form-data",type='post' <form action='uploadFile.php' enctype="multipart/form-data" type='post'> <input type='file'> <input type=

springboot上传文件 &amp; 不配置虚拟路径访问服务器图片 &amp; springboot配置日期的格式化方式

1.    Springboot上传文件 springboot的文件上传不用配置拦截器,其上传方法与SpringMVC一样 @RequestMapping("/uploadPicture") @ResponseBody public JSONResultUtil uploadPicture(MultipartFile file, Integer viewId) { if (file == null) { return JSONResultUtil.error("文件没接到&q

spring-boot上传文件MultiPartFile获取不到文件问题解决

1.现象是在spring-boot里加入commons-fileupload jar并且配置了mutilPart的bean,在upload的POST请求后,发现 multipartRequest.getFiles("file")=null,有点奇怪,查了文档资料才解决. [java] view plain copy <bean id="multipartResolver" class="org.springframework.web.multipar

phpcms前端页面上传文件

PHPCMS其实有一个叫做附件的模块,上传用的就是这个东西,现在我们来看一下对应的文件:phpcms\modules\attachment \attachments.php就是这个文件,大概在29行上(我用的PHPCMS版本号是Phpcms V9.5.8 Release 20140929)有下面一个方法: public function upload() { $grouplist = getcache('grouplist','member'); //获取缓存中身份分组的列表 if($this-

前端之web上传文件的方式

前端之web上传文件的方式 本节内容 web上传文件方式介绍 form上传文件 原生js实现ajax上传文件 jquery实现ajax上传文件 form+iframe构造请求上传文件 1. web上传文件方式介绍 在web浏览器上传文件一般有以下几种方式: form表单上传文件 原生js实现ajax上传文件 jquery实现ajax上传文件 form+iframe上传文件 其中form提交数据之后会整个刷新页面:js通过ajax上传文件虽然不会刷新整个页面,但是他们都是通过使用formdata对