首先element-ui中的上传组件是这样的
数据结构:
{
action:“”//上传的连接
filelist:'‘’//选种的文件集合
}
<el-upload
class="upload-demo"
action="https://jsonplaceholder.typicode.com/posts/"
:on-preview="handlePreview"
:on-remove="handleRemove"
:before-remove="beforeRemove"
multiple
:limit="3"
:on-exceed="handleExceed"
:file-list="fileList">
<el-button size="small" type="primary">点击上传el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kbdiv>
el-upload>
点击按钮后就自动根据action的地址上传,实际上是element-ui自动发送了post请求给action连接,但是我想要通过自己手动上传文件(图片/excel)
直接发送这个文件体
upload(){
this.request.post('/manage/uploadExcel',this.filelist).then(res=>{
alert(res.code)
})
},
游览器发现无负载,并且前端已经自动发送了一次请求给action,如果把action参数取消,控制台还会报错
为了实现手动上传文件,需要添加
实现方法:因为直接只用filelist发送请求时无法携带的,所以就用自定义方法接受filelist的文件
<el-upload
class="upload-demo"
:on-preview="handlePreview"
:on-remove="handleRemove"
:before-remove="beforeRemove"
multiple
:action="null"
:http-request="fileupdate"
:limit="3"
:on-exceed="handleExceed"
:file-list="fileList">
<el-button size="small" type="primary" >导入excel数据 <i class="el-icon-circle-plus-outline">i>el-button>
el-upload>
fileupdate方法
fileupdate(item){
this.model=item.file
},
此时文件就已经赋值给自定义的数组model
再次使用axios发送post请求
upload(){
this.request.post('/manage/uploadExcel',this.model).then(res=>{
alert(res.code)
})
成功
第二种方法
关闭自动上传 手动按钮上传 :auto-upload=“false”
<el-upload
class="upload-demo"
action=""
:on-preview="handlePreview"
:on-remove="handleRemove"
ref="upload"
:before-remove="beforeRemove"
:auto-upload="false"
multiple
:limit="3"
:on-success="handle_success"
:on-exceed="handleExceed"
:file-list="fileList">
<el-button slot="trigger" size="small" type="primary">选取文件el-button>
<el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kbdiv>
时间处理 axios提交请求
submitUpload() {
//this.$refs.upload.submit();
let file = this.$refs.upload.uploadFiles.pop().raw;//这里获取上传的文件对象
let formData = new FormData();
formData.append("file",file);
this.request.post("/app/uploadFiles",formData).then(res=>{
this.$message.success(res.data)
})},
其中如果图片是上传oss
**:on-success=“handle_success”**可以写入上传成功的逻辑
//和axios一样的回调
handle_success(res) {
console.log(res)
this.$message.success('图片上传成功')
},