#简单记录下
前言
前段时间公司给的项目里刚好有个上传的功能,询问过需求后是要多文件上传,刚入行的前端菜鸟,啥也不会,查看各种文档,最后终于弄了出来,最近开始闲下来没啥事,就把之前写的上传记录下来,说不定以后还要回来瞅瞅. 想看原始方法的可以去这个
前期引入elementui就不做简述了,官网
说明
之所以要这么写是因为elementui上传组件在多文件上传时,是每一个文件调用一次接口,虽然表面上看起来是多文件是一次上传的,但实际是每一个都单独的调用了一次接口,所以就有了如下写法。
Dome
<el-form-item label="上传附件:" prop="cover" style="margin-top: 20px">
<el-upload class="avatar-uploader" ref="upload" action="" :show-file-list="true" :on-success="handleAvatarSuccess" multiple :limit="5" :on-progress="onProgress" :auto-upload='false' :on-change="OnChange" :on-remove="OnRemove" :http-request="uploadFile" :before-upload="beforeAvatarUpload" name="file" list-type="picture-card" :file-list="fileList" accept=".doc,.docx,.pdf,.zip,.rar">
<img v-if="imageUrl" :src="imageUrl" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
<el-progress v-if="videoFlag == true" type="circle" :percentage="percent" style="top:-89%;">
</el-progress>
</el-upload>
</el-form-item>
<el-form-item>
<el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">确定
</el-button>
<el-button @click="cancel" size="mini">取消</el-button>
</el-form-item>
表格
| 参数 | 说明 | 类型 |
|---|---|---|
| show-file-list | 是否显示已上传文件列表 | boolean |
| multiple | 是否支持多文件 | boolean |
| on-success | 文件上传成功时的钩子 | function(response, file, fileList) |
| limit | 最大允许上传个数 | number |
| on-progress | 文件上传时的钩子 | function(event, file, fileList) |
| http-request | 覆盖默认的上传行为,可以自定义上传的实现 | function |
| auto-upload | 是否在选取文件后立即进行上传 | boolean |
| on-change | 文件状态改变时的钩子,添加文件、上传成功和上传失败时都会被调用 | function(file, fileList) |
| on-remove | 文件列表移除文件时的钩子 | function(file, fileList) |
| before-upload | 上传文件之前的钩子,参数为上传的文件,若返回 false 或者返回 Promise 且被 reject,则停止上传 | function(file) |
| file-list | 上传的文件列表, 例如: [{name: 'food.jpg', url: 'xxx.cdn.com/xxx.jpg'}] | array |
上面的参数有很多都没怎么用到,在elementui-Upload里有更详细的使用方法,在这里就不过多说明。
js
export default {
//name放入模板名,方便在其他地方引用
name: '',
//import引入的组件需要注入到对象中才能使用
components: {},
data() {
//这里存放数据
return {
fileList: [], //文件存储中间量
imageUrl: "",//上传时展示图件图片,在这里我上传的是文件没有图片类型的,就无法展示出来
};
},
//监听属性 类似于data概念
omputed: {
},
//生命周期 - 创建完成(可以访问当前this实例)
created() {
},
//生命周期 - 挂载完成(可以访问DOM元素)
mounted() {
},
//方法集合
methods: {
//隐藏
// 取消
cancel() {
this.fileList = []
},
//file选择新文件,fileList已经选择后的文件 文件状态改变
OnChange(file, fileList) {
this.fileList = fileList
},
//文件移除
OnRemove(file, fileList) {
this.fileList = fileList
},
//覆盖默认上传,自定义方法
uploadFile() {
let _this = this
let file = this.fileList
/*
使用formdata 由单文件对象变为多文件数组,然后进行遍历处理。
可以通过get(key)与getAll(key)来获取相对应的值
*/
var formdata = new FormData();
let set = new Set(file)
var fill = {}
set.forEach(fil => {
fill = fil.raw
formdata.append("fileList", fil.raw);
});
if (fill.length != 0) {
axios.post("上传地址", formdata, {
onUploadProgress(progressEvent) {
if (progressEvent.lengthComputable) {
let val = (progressEvent.loaded / progressEvent.total * 100).toFixed(0) //获取百分比
//progressEvent.loaded 上传到服务器多少秒
//progressEvent.total 图片总大小
var percent = parseInt(val)
}
//调用文件上传时钩子
this.onProgress(percent)
}
}).then(res => {
this.form.guid = res.data.message
this.handleAvatarSuccess(res.data)
}).catch(res => {
// console.log(res)
})
} else if (fill.length == 0) {
_this.$message({
type: "info",
message: '请上传文件'
})
}
},
//上传服务器
submitUpload() {
let _this = this
this.uploadFile()
},
//文件上传时
onProgress(event) {
// console.log('进度条')
// console.log(event)
this.videoFlag = true
this.percent = event
},
//确定
onSubmit(formName) {
let _this = this;;
let baocun = {};
_this.form.formType = _this.fater
_this.form.city = this.getCache('login').user.extend.extendS1
_this.form.county = this.getCache('login').user.extend.extendS2
baocun = _this.form;
upSave(baocun).then(res => {
_this.$message({
type: "success",
message: res.message
});
// _this.init()
_this.form = {}
_this.$emit('onsubmit',true)
// _this.showLoding = false
})
.catch(e => {
// console.log(e)
_this.$message({
type: "info",
message: "已取消保存"
});
});
},
// 上传相关
//上传中回调
handleAvatarzhong() {},
// 成功回调
handleAvatarSuccess(res, file) {
let _this = this
_this.videoFlag = false
this.$refs.upload.clearFiles()
this.fileList = []
if (res.code == "0") {
_this.$message({
type: "success",
message: res.message
});
_this.onSubmit()
} else {
_this.$message({
type: "success",
message: res.message
});
}
_this.fileList = []
},
//设置上传的大小限制
beforeAvatarUpload(file, fileList) {
const isLt500M = file.size / 1024 / 1024 < 1020;
if (!isLt500M) {
this.$message.error('上传文件大小不能超过 1020MB!');
}
return isLt500M;
},
},
//监控data中的数据变化
watch: {
},
//如果页面有keep-alive缓存功能,这个函数会触发
activated() {
},
}