通过el-upload同时上传表单和文件
- 上传前,el-upload组件选哟
- 设置on-change,在上传时检测是文件是否符合标准(格式、大小),不符合标准在fileLIst中删去并用$message弹出错误
- 关闭el-upload的自动上传
- 设置accept,选择可以请求的文件类型
- 将action设为空
- 上传时,需要在提交请求前处理文件
- 设置一个新的formData格式的变量,将文件加入其中,再将其赋值给传递的变量
- 在接口处,设置header中content-type属性为
multipart/form-data
<template>
<div class="test">
<el-form
enctype="multipart/form-data"
label-position="left"
label-width="96px"
:model="PastureForm"
style="width: 400px"
>
<el-form-item label="图片资料">
<el-upload
class="upload-pasture"
ref="pastureImgUpload"
accept=".jpg, .jpeg, .png"
action=""
:limit="1"
:file-list="pastureimgList"
:on-change="handleimgChange"
:auto-upload="false"
drag
>
<i class="el-icon-upload"></i>
<div class="el-upload__text">将图片拖到此处,或<em>点击上传</em></div>
<div class="el-upload__tip" slot="tip">
只能上传一张jpg/jpeg/png图片
</div>
</el-upload>
</el-form-item>
<el-form-item label="视频资料">
<el-upload
class="upload-pasture"
ref="pastureVideoUpload"
accept=".mp4"
action=""
:limit="1"
:file-list="pasturevideoList"
:on-change="handlevideoChange"
:auto-upload="false"
drag
>
<i class="el-icon-upload"></i>
<div class="el-upload__text">将视频拖到此处,或<em>点击上传</em></div>
<div class="el-upload__tip" slot="tip">
只能上传mp4视频
</div>
</el-upload>
</el-form-item>
</el-form>
<span slot="footer" class="dialog-footer">
<el-button type="primary" @click="postPasture()">添 加</el-button>
</span>
</div>
</template>
<script>
import { addPasture } from '@/api/post'
export default {
data() {
return {
PastureForm: {
addressId:1,
enterpriseId:1,
sowName:"苜蓿",
sowRate:100,
sowTime:"2022-04-39 20:00:00",
unit:"斤/亩",
},
pastureimgList: [],
pasturevideoList: []
}
},
methods:{
postPasture(){
console.log(this.pastureimgList[0])
let formData = new FormData();
formData.append('pictureFile', this.pastureimgList[0].raw);
this.PastureForm.pictureUrl = formData
let formData2 = new FormData()
formData2.append('videoFile', this.pasturevideoList[0]);
this.PastureForm.videoUrl = formData2
let file = new FormData();
file.append('pictureFile', this.pastureimgList[0].raw)
file.append('videoFile', this.pasturevideoList[0].raw);
this.PastureForm.file = file
addPasture(this.PastureForm).then(Response =>{
console.log(Response.data)
})
},
delFile() {
this.pastureimgList = [];
},
handleimgChange(file, fileList) {
this.pastureimgList = fileList;
},
handlevideoChange(file, fileList) {
this.pasturevideoList = fileList;
},
handleRemove(file, fileList) {
console.log(file, fileList);
},
handlePreview(file) {
console.log(file);
},
}
};
</script>
<style scoped>
.test{
margin:50px 100px;
}
</style>
export function addPasture(params){
console.log(params)
return request({
headers:{
'Content-Type': 'multipart/form-data'
},
url:'/pasture/plating/add',
method:'post',
params,
data: params.file
})
}