使用axios将前端fom-data数据发送到后端

前言

  • 本方法基于前后端分离开发

  • 前端使用vue2.0,CLI脚手架搭建

  • 后端使用Java语言,Maven项目,sping SSM框架。

一、基本配置

(一)后端服务器

(1)引入依赖:
  • file-upload 1.3.1

  • commons-io 2.5

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.3.26}</version>
</dependency>

<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
</dependency>

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.5</version>
</dependency>
(2)spirngMVC 配置文件
  • 配置文件传输解析器

<!-- 配置文件传输解析器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize" value="104857600"/>
    <property name="maxInMemorySize" value="4096"/>
    <property name="defaultEncoding" value="UTF-8"/>
</bean>
  • 配置跨域访问cors

<!-- 全局配置cors -->
<!-- 其中:
  allowed-origins 为允许的访问源地址(*为所有请求)
  allowed-methods 为允许访问方式
  allow-credentials 为允许携带cookies(允许时origins不能为*)
  exposed-headers 为响应携带的头部
  allowed-origin-patterns 可以使访问源自动添加至允许的地址中
 -->
<mvc:cors>
    <mvc:mapping path="/**"
                 allowed-origin-patterns="*"
                 allow-credentials="true"
                 allowed-origins=""
                 allowed-headers="*"
                 />
</mvc:cors>

(二)前端vue脚手架

(1)安装axios

npm install axios

(2)安装element-ui

npm i element-ui -S

二、代码实现上传单个文件实体

(一)后端服务器控制层

@Controller
public class TestController {
    @RequestMapping("/upload/test1")
    @ResponseBody
    public void uploadTest(@RequestParam("file") MultipartFile multipartFile){
        System.out.println("uploadTest");
        System.out.println("file="+multipartFile);
    }
}

(二)前端vue页面

postForm方法只是对应的 post方法,其 content-type 头部默认设为multipart/form-data

<template>
    <el-container>
        <el-header>
            <h1>测试</h1>
        </el-header>
        <el-main>
            <el-row type="flex" justify="center">
                <el-col :span="12">
                    <el-upload class="avatar-uploader" :auto-upload="false" :multiple="false" :show-file-list="false" :on-change="getImg">
                        <el-image class="avatar" v-if="imageUrl" :src="imageUrl" fit="fill"/>
                        <i v-if="!imageUrl" class="el-icon-plus avatar-uploader-icon"/>
                    </el-upload>
                    <el-button @click="imageUrl = '';file = ''">重新上传</el-button>
                    <el-button @click="uploadImg">上传至服务器</el-button>
                </el-col>
            </el-row>
        </el-main>
    </el-container>
</template>
​
<script>
    export default {
        data() {
            return {
                imageUrl: '',
                file:'',
            }
        },
        methods: {
            getImg(file,fileList){
                this.file = file.raw;
                this.imageUrl = URL.createObjectURL(this.file);
            },
            uploadImg(){
                console.log(this.file);
                this.$axios.postForm('/upload/test1',{
                    file:this.file
                });
            }
        }
    }
</script>
​
<style scoped>
    .avatar-uploader i{
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        border-color: #409EFF;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        margin: 0;
        padding: 1px;
    }
    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 150px;
        height: 150px;
        line-height: 150px; 
        text-align: center;
    }
    .avatar {
        width: 150px;
        height: 150px;
        display: block;
    }
</style>

(三)测试结果

uploadTest file=MultipartFile[field="file", filename=你上传的图片名字.图片格式, contentType=image/jpeg, size=58751]

三、包含文件实体和其他数据的混合表单上传

(一)前端Vue页面方法

  • 将文件和数据直接放到一起,使用axios的postForm上传即可(axios内置方法直接将数据序列化)

uploadImg(){
    this.$axios.postForm('/upload/test3',{
        file1:this.file1,
        file2:this.file2,
        userId:1
    });
}

(二)后端服务器控制层

  • 注意此时要使用MultipartHttpServletRequest接口

  • 获取其中的文件map使用上述接口的getMultiFileMap()方法

  • 获取其中的参数使用上述接口的getParameter(参数名)方法,注意此处不能使用getParameterMap()方法,因返回的Map对象是<String,String[]>格式。不方便取其中值

@Controller
public class TestController {
    @RequestMapping("/upload/test3")
    public void uploadTest3(MultipartHttpServletRequest req){
        System.out.println("upload test 3");
        MultiValueMap<String, MultipartFile> multiFileMap = req.getMultiFileMap();
        System.out.println(multiFileMap);
        System.out.println("");
        String userId = req.getParameter("userId");
        System.out.println(userId);
    }
}

(三)测试结果

upload test 3 {file1=[MultipartFile[field="file1", filename=0f4bd884-dc9c-4cf9-b59e-7d5958fec3dd.jpg, contentType=image/jpeg, size=117856]], file2=[MultipartFile[field="file2", filename=2a50628e-7758-4c51-9fbb-d37c61cdacad.jpg, contentType=image/jpeg, size=84907]]} ​

1

 

参考资料

Blob - Web API 接口参考 | MDN (mozilla.org)

File - Web API 接口参考 | MDN (mozilla.org)

FileReader - Web API 接口参考 | MDN (mozilla.org)

Multipart 实体请求 | Axios中文文档 | Axios中文网 (axios-http.cn)

组件 | Element

如何用SpringBoot框架来接收multipart/form-data文件_springboot multipart/form-data-CSDN博客

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值