VUE+ElementUI重写默认上传方式
下面是elementUI官网的demo<el-uploadclass="upload-demo"ref="upload"action="https://jsonplaceholder.typicode.com/posts/":on-preview="handlePreview":on-remove="handleRemove":file-list=...
·
下面是elementUI官网的demo
<el-upload class="upload-demo" ref="upload" action="https://jsonplaceholder.typicode.com/posts/" :on-preview="handlePreview" :on-remove="handleRemove" :file-list="fileList" :auto-upload="false"> <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文件,且不超过500kb</div> </el-upload>
根据官网文档,action是一个必选参数,来指定文件上传路径
但是我们在结合VUE和nodeJS的时候,发现这样并不是很方便,因为我们与后台的接口的交互,都统一的放在了axios里管理了
upload_info: {url: process.env.API_HOST+"/xxxx/import", method: 'post'}
如果单独在action里写url,根据我实验,也不会出什么问题,但是后期的维护就是个大问题了,所以我查了一些资料再加上官方文档的帮助,重写了一下默认的上传方式,而这得益于下面的参数
所以我们整理一下上面的代码:
<el-upload
class="upload-demo"
ref="upload"
limit=1
:http-request="uploadSectionFile"
:on-preview="handlePreview"
:on-remove="handleRemove"
:auto-upload="false">
<el-button slot="trigger" size="small" type="primary">选取文件</el-button>
<div slot="tip" class="el-upload__tip"></div>
</el-upload>
:http-request="uploadSectionFile"
:on-preview="handlePreview"
:on-remove="handleRemove"
:auto-upload="false">
<el-button slot="trigger" size="small" type="primary">选取文件</el-button>
<div slot="tip" class="el-upload__tip"></div>
</el-upload>
注意红色的部分,以及我们去掉了action。我们重新指定了一个方法
<script>
export default {
methods: {
uploadSectionFile:function (param) {
//file就是当前添加的文件
var fileObj = param.file;
// FormData 对象
var form = new FormData();
// 文件对象,key是后台接受的参数名称
form.append("uploadFile", fileObj);
this.net.upload_carIllegalBehavior_info(form).then((res) =>{
// 这里做上传后的操作
});
},
submitUpload() {
this.$refs.upload.submit();
},
handleRemove(file, fileList) {
console.log(file, fileList);
},
handlePreview(file) {
console.log(file);
}
}
}
</script>
uploadSectionFile:function (param) {
//file就是当前添加的文件
var fileObj = param.file;
// FormData 对象
var form = new FormData();
// 文件对象,key是后台接受的参数名称
form.append("uploadFile", fileObj);
this.net.upload_carIllegalBehavior_info(form).then((res) =>{
// 这里做上传后的操作
});
},
submitUpload() {
this.$refs.upload.submit();
},
handleRemove(file, fileList) {
console.log(file, fileList);
},
handlePreview(file) {
console.log(file);
}
}
}
</script>
更多推荐
已为社区贡献5条内容
所有评论(0)