|
阅读:4589回复:0
vue + elementui + axios表单数据和文件上传
实现的功能:
1、表单数据提交, 2、表单中携带文件附件。 3、附件上传过程中进度提示。 前端使用:vue + elementui + axios VUE代码 <el-form-item label="作品上传:" prop="files" size = 'small' > <el-upload ref="upload_attach" class="upload-demo" action="/user/apply" multiple accept=".zip,.rar,.7z" :limit="1" :on-change="changFile" :on-exceed="handleExceed" :file-list="fileList" :auto-upload="false"> <el-button slot="trigger" size="small" type="primary">选取文件</el-button> <div slot="tip" class="el-upload__tip">注:上传的文件须是压缩文件格式,且不超过50M</div> </el-upload> </el-form-item> methods中定义的方法 changFile(file, fileList) { console.log(fileList); //选择文件后,给fileList对象赋值 this.fileList = fileList }, 提交上传 apply(){ let data = new FormData(); // todo 非常重要,一定要加file.raw,从浏览器中查看需要使用binary类型,后台才能正确接收 this.form.files = this.fileList[0].raw console.log(this.fileList[0].raw) // 将form表单中的值都赋值给FormData传递给后台 for(let key in this.form){ console.log(this.form[key]) data.append(key,this.form[key]) } this.$axios .post('/user/apply',data,{ headers: { 'Content-Type': 'multipart/form-data' }})// 第一种,直就传个json数据,不需要设置headers // .post('/user/apply',this.form)// 第三种,可以直接传递这个form(推荐) .then(resp => { console.log('请求本地接口OK') console.log(resp) if(resp.data.code == -1){ // 接口返回-1,就是注册失败,提示消息提示用户 this.$message({ message: resp.data.msg, type: 'error' }); } else if(resp.data.code == 0){ console.log(resp.data) //注册成功 this.$message({ message: "sh成功", type: 'success' }); // 跳转到登录页面 // this.$router.push('/login') } }) .catch(function (error) { // 请求失败处理 console.log('请求本地接口失败' + error); }); }, 特别需要注意:这样才能取到文件对象 this.form.files = this.fileList[0].raw 这里我记录我用过的一中方法,原文还有第二种 文章转载: (4条消息) vue + elementui + axios表单数据和文件上传_pinqiang的博客-CSDN博客 |
|