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,实在看不懂的话可以按照我的配置来写。

相关推荐
风骏时光牛马2 小时前
AI多模块协同自动化工作流
前端
zhangminghuan2 小时前
前端面试应对技巧
前端·面试·职场和发展
计算机魔术师2 小时前
潜伏14年的PHP致命洞,AI跑两天就交卷了
前端
IT_陈寒2 小时前
Vue的这个响应式陷阱我居然现在才发现
前端·人工智能·后端
Python自动化直播3 小时前
智能脚本批量管理拆开看:导入、导出、重写、试听
前端·python·ai·秒播
开开心心就好4 小时前
发票信息录入太麻烦?离线工具一键转表格
运维·服务器·前端·pdf·ocr·maven·intellij-idea
এ慕ོ冬℘゜4 小时前
ES Promise.all/ Promise.race
前端·javascript·elasticsearch
喜欢打篮球的普通人5 小时前
LLVM 前端与优化层:Clang 如何把 C 代码变成 IR
c语言·前端·状态模式
大文说跨境5 小时前
亚马逊多店铺用过多款指纹浏览器,说点长期用的实际感受
前端·网络