Vue+axios使用FormData方式向后端发送数据

前言

在前后端分离的项目中经常使用到Vue+axios通过FormData的方式向后端(Java)发送表单数据(文字+图片),但是在初次写这个功能时,可能会遇到很多问题,本文详细的记录了该功能的实现。


一、🥙该功能应用场景

前端向后端发送表单数据时,可能会同时发送图片和文本,这时会有一些需要注意的小细节。

二、🥗代码示例

1.前端(使用的ant-design-vue,element-ui同理)

代码如下(示例):

html 复制代码
<template>
  <a-form-model :model="form" :label-col="labelCol" :wrapper-col="wrapperCol">
    <a-form-model-item label="标题">
      <a-input v-model="form.title"/>
    </a-form-model-item>
    <a-form-model-item label="作者">
      <a-input v-model="form.author"/>
    </a-form-model-item>
    <a-form-model-item label="类型">
      <a-radio-group v-model="form.tag">
        <a-radio :style="radioStyle" :value="1">
          生活
        </a-radio>
        <a-radio :style="radioStyle" :value="2">
          学习
        </a-radio>
        <a-radio :style="radioStyle" :value="3">
          社会
        </a-radio>
      </a-radio-group>
    </a-form-model-item>
    <a-form-model-item label="图片资源">
    //此处开启了多选,并重写了brforeUpload方法,为了关闭自动提交和将图片转换为base64编码,同时声明了文件列表的类型
      <a-upload
          :multiple="true"
          :before-upload="beforeUpload"
          name="file"
          list-type="picture"
      >
        <a-button>
          <a-icon type="upload"/>
          上传推文图片
        </a-button>
      </a-upload>
    </a-form-model-item>
    <a-form-model-item label="正文">
      <a-input v-model="form.content" type="textarea"/>
    </a-form-model-item>
    <a-form-model-item :wrapper-col="{ span: 14, offset: 4 }">
      <a-button type="primary" @click="onSubmit">
        提交
      </a-button>
    </a-form-model-item>
  </a-form-model>
</template>
<script>
import axios from "axios";

export default {
  data() {
    return {
      value: 1,
      radioStyle: {
        display: 'inline',
        height: '30px',
        lineHeight: '30px',
      },
      labelCol: {span: 4},
      wrapperCol: {span: 14},
      form: {
        title: '',
        author: '',
        tag: '',
        fileList: [],
        content: ''
      }
    };
  },
  methods: {
    beforeUpload(file, fileList) {
    //将图片转换为Base64编码
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = () => {
        const base64 = reader.result;
        this.form.fileList.push(base64)
      };
      console.log(this.form.fileList)
       //禁止直接提交图片
      return false;
    },
    //提交表单
    onSubmit() {
      let formData = new FormData
      //此处需要和后端接收的参数名相同
      formData.append("form", JSON.stringify(this.form))
      axios.post(
      	  //后端接口,自行修改
          " http://localhost:8081/manage/submit",
          formData,
          {
            headers: {'Content-Type': 'multipart/form-data'}
          }
      ).then(res => {
        console.log(res.data.message)
      })
    },
  },
};
</script>

该段代码效果图:

2.后端

代码如下(示例):

java 复制代码
@RestController
@Slf4j
@RequestMapping("/manage")
@CrossOrigin
public class ManageArticleController {
    @Resource
    ArticleService articleService;

    @PostMapping("/submit")
    public SystemResult<String> uploadImages(@RequestParam("form") String form)throws Exception {
    //这儿将传入的参数转换为对应的实体类
        ArticleVo articleVo=JSON.parseObject(form,ArticleVo.class);
        return SystemResult.success("上传成功");
    }
}

实体类:

java 复制代码
@Data
@Accessors(chain = true)
@AllArgsConstructor
@NoArgsConstructor
//对应的实体类
public class ArticleVo implements Serializable {
    private String title;
    private String author;
    private int tag;
    private List<String> fileList;
    private String content;
}

三、🥫效果演示

前端向后端发送数据,后端打印显示 在传入到后端后,可以自行根据需求将数据存入数据库

四、🌯问题总结

  1. 前端发送的字段名和后端实体类的字段名不一致

​ 将前端发送的数据名称和后端修改一致

  1. 跨域问题

​ 后端接口上添加注解@CrossOrigin

  1. 文件上传的限制问题

​ 在后端做相应的文件上传配置,比如上传大小,或者前端也做相应的验证。

  1. 不了解upload组件相关接口,导致功能无法实现

​ 前往官网查看对应组件的api,实在看不懂的话可以按照我的配置来写。

相关推荐
NiceCloud喜云5 小时前
Opus 4.8 的 Effort Control 怎么选:Low 到 Max 五档策略
android·java·大数据·前端·c++·python·spring
wordbaby6 小时前
React Native + RNOH:跨页面数据回传的最佳实践与避坑指南
前端·react native
丷丩6 小时前
MapLibre GL JS第22课:查看本地GeoJSON
前端·javascript·map·mapbox·maplibre gl js
Front思7 小时前
AI前端工程师需要具备能力+
前端·人工智能·ai
ZC跨境爬虫9 小时前
跟着 MDN 学CSS day_29:(掌握文本与字体样式的核心艺术)
前端·css·ui·html·tensorflow
李子琪。10 小时前
网络空间安全深度实战:CSRF 漏洞原理剖析与基于 Token 的纵深防御体系构建(全栈实验报告)
前端·安全·csrf
冰暮流星10 小时前
javascript之history对象介绍
前端·笔记
IT_陈寒10 小时前
Vite热更新失灵?你可能漏了这个配置
前端·人工智能·后端
丷丩10 小时前
MapLibre GL JS第19课:实时更新要素
前端·javascript·gis·map·mapbox·maplibre gl js
Mr.Daozhi10 小时前
RAG 进阶实战:跑通 Demo 后我连续翻了 6 次车,逐一修复才真正可用(含 Gradio Web 版)
前端·数据库·langchain·大模型·gradio·rag·科研工具