前端通过axios和FormData实现文件上传功能遇到的坑

使用element-ui中的upload上传组件,前端上传数据参数已经传过去了,但是后端 (java) 接不到数据 (null)

【解决方案】

html部分: 

       <el-button type="primary" v-show="type!=2" @click="updateActivity(1)">保存</el-button>

       <
div class="uploadBox tx-lf"> <div class="fileBox"> 模板导入 <input type="file" name="commodityFile" id="commodityFile" class="fileBtn" @change="uploadChange" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"> </div> <div class="el-upload__tip">只能上传xlsx文件,且不超过10M</div> <div class="filename">{{fileName}}</div> </div>

css部分:

     .fileBox{
            width: 48px;
            height: 14px;
            padding: 9px 15px;
            font-size: 12px;
            position: relative;
            overflow: hidden;
            color: #fff;
            background-color: #409EFF;
            border-color: #409EFF;
            border-radius: 3px;
            .fileBtn{
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                outline: none;
                background: transparent;
                filter: alpha(opacity=0);
                -moz-opacity: 0;
                -khtml-opacity: 0;
                opacity: 0;
            }
        }

js部分:

     updateActivity(status){
            //判断文件大小   文件不能超过10MB
            let file = document.getElementById("commodityFile").files[0]?document.getElementById("commodityFile").files[0]:'';
            if(file){
                const isLt10M = file.size / 1024 / 1024 < 10;
                if (!isLt10M) {
                      this.$message.error('上传文件大小不能超过 10MB!');
                      return false;
                }
            }
            let styleNos = [];
            if(this.tableData.length > 0){
                this.tableData.forEach(item => {
                    styleNos.push(item.styleNo);
                })
            }
            var form = new FormData();
            form.append('activityName',this.formInline.activityName);
            form.append('status',status);
            form.append('startTime',this.formInline.startTime);
            form.append('endTime',this.formInline.endTime);
            form.append('tagId',this.formInline.tagId);
            form.append('id',this.formInline.id);
            form.append('styleNos',styleNos);
            form.append("commodityFile", file);
            this.axios.defaults.headers.post['Content-Type']='multipart/form-data;charse=UTF-8';
        this.axios({
                method: 'post',
                data: form,
                transformRequest: [function(){
                    return form;
                }],
                url: '/activity/updateActivity',
            })
            .then(res => {
                res = res.data;
                if(res.state == 'success'){
                    this.$message.success(res.data);
                }else{
                    this.$message.error(res.data);
                }
            });
        },

 

参考文章: https://blog.csdn.net/weixin_34413802/article/details/88722992

转载于:https://www.cnblogs.com/rachelch/p/11063572.html

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: axios可以通过FormData对象上文件,具体步骤如下: 1. 创建FormData对象 ``` const formData = new FormData(); ``` 2. 添加文件FormData对象中 ``` formData.append('file', file); ``` 其中,'file'是上文件的字段名,file是要上文件对象。 3. 发送请求 ``` axios.post('/upload', formData, { headers: { 'Content-Type': 'multipart/form-data' } }).then(response => { console.log(response); }).catch(error => { console.log(error); }); ``` 其中,'/upload'是上文件的接口地址,headers中的'Content-Type'必须设置为'multipart/form-data',否则服务器无法正确解析上文件。 以上就是使用axios文件的基本步骤。 ### 回答2: axios是现在使用最为广泛的HTTP客户端请求库,提供了方便易用的API,使用axios可以方便的进行数据的获取和提交,而且还支持跨域请求和CSRF攻击保护。 但是在上文件时,需要使用FormData类型的数据格式进行提交,axios也提供了很好的支持。下面我们来介绍一下axios如何上FormData类型的数据。 1. 首先需要创建FormData对象,将要上的参数和文件添加到FormData中。 ``` let formData = new FormData(); formData.append('name', 'axios_upload_file'); // 添加普通参数 formData.append('file', file); // 添加要上文件 ``` 2. 创建axios实例,设置请求的参数,包括请求的URL、请求的方式、请求的数据等。需要注意的是,设置Content-Type为'multipart/form-data',这样后端服务才能正确解析请求的参数和文件。 ``` const instance = axios.create({ baseURL: 'http://localhost:3000', // 设置请求的baseURL timeout: 10000, // 设置请求的超时时间 headers: {'Content-Type': 'multipart/form-data'} // 设置请求头类型为form-data }); ``` 3. 使用axios实例发送请求,可以使用post或者put请求。FormData对象作为第二个参数。需要注意的是,不需要手动设置请求头中的Content-Type和Content-Length参数,axios会自动设置这些参数。 ``` instance.post('/upload', formData).then(res => { console.log(res); }).catch(err => { console.error(err); }) ``` 4. 接收后台返回的数据。使用then和catch方法异步处理后台返回的数据。 ``` .then(res => { console.log(res.data); }).catch(err => { console.error(err); }) ``` 以上就是使用axiosFormData类型的文件的步骤和注意事项了。我们需要注意,上文件时,需要在服务端配置文件的接收处理逻辑,一般情况下需要使用multer库或其他类似的中间件,来实现文件相关功能。 ### 回答3: Axios是一个非常流行的JavaScript库,主要用于向服务器发起HTTP请求和处理响应。Axios支持各种HTTP请求和响应类型,包括文件和下载。 File Upload FormData(表单数据)是一种简单易用的方法来上文件FormData对象允许我们在发送XMLHttpRequest请求时添加文件以及其他类型的数据。 以下是使用Axios实现文件的基本步骤: 1. 创建一个FormData对象。 ``` var formData = new FormData(); ``` 2. 将要上文件添加到FormData对象中。 ``` formData.append('file', file); ``` 3. 发送Ajax请求,使用Axios发送FormData对象。 ``` axios.post('/url', formData, { headers: { 'Content-Type': 'multipart/form-data' } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); ``` 在这个请求中,我们使用“POST”HTTP方法提交FormData对象,其中包含我们要上文件。我们还指定了Content-Type头文件类型为“multipart/form-data”。 如果文件成功,我们将在响应中获得服务器返回的结果。如果出现错误,我们可以通过捕获Axios Promise中的错误来进行处理。 总结:使用Axios文件的方式非常简单,只需要创建一个FormData对象,把要上文件添加到FormData对象中,然后使用Axios发送Ajax请求即可。Axios可以处理各种HTTP请求和响应类型,因此它是处理文件的绝佳工具。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值