<template>
<el-upload
ref="upload"
action
accept="application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
:limit="1"
:file-list="fileList"
:auto-upload="false"
:before-upload="beforeUpload"
:before-remove="beforeRemove"
:on-exceed="handleExceed"
:on-change="change"
:on-preview="preview"
:on-progress="progress"
:on-success="success"
:on-error="error"
:http-request="fileUpload"
>
<el-button type="success" size="large" :disabled="selectFileList.length > 0">选择上传文件(Excel文件)</el-button>
</el-upload>
</template>
<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import { Upload } from 'element-ui';
import axios from 'axios';
@Component({
name: 'FileUpload'
})
export default class extends Vue {
//上传文件列表
private fileList: any[] = [];
//已选择的文件列表
private selectFileList: any[] = [];
//上传中状态
private uploading: boolean = false;
//点击文件列表中已上传的文件时
private preview(file) {
console.log( file);
}
//文件列表移除文件时
private beforeRemove(file, fileList) {
console.log( file, fileList);
}
//文件上传前 限制格式和大小
private beforeUpload(file: any) {
//const isJPG = file.type === 'image/jpeg';
// if (!isJPG) {
// this.$message.error('上传文件只能是 JPG 格式!');
// }
let maxSize = 1; //文件最大MB
const isExceedMaxSize = file.size / 1024 / 1024 > maxSize; //是否超出大小限制
if (isExceedMaxSize) {
this.$message.error('文件大小不能超过 ' + maxSize + 'MB!');
}
}
//文件上传
private fileUpload(config: any) {
let formData = new FormData();
formData.append('file', config.file);
this.uploading = true;
axios
.post('http://www.lihefei.com/upload',
formData
)
.then((resolve: any) => {
console.log(resolve.data);
})
.then(() => {
this.uploading = false;
});
}
//文件状态改变
private change(file: any, fileList: any) {
this.selectFileList = fileList;
}
//点击文件列表中已上传的文件时
private preview(file: any) {
console.log(file);
}
//文件上传进度
private progress(event: any, file: any, fileList: any[]) {
console.log(event, file, fileList);
}
//图片上传成功
private success(response: any, file: any, fileList: any[]) {
console.log(response, file, fileList);
}
//图片上传失败
private error(err: any, file: any, fileList: any[]) {
console.log(err, file, fileList);
}
//清空已上传的文件列表
private clearFiles() {
(this.$refs.upload as Upload).clearFiles();
}
//文件超出限制控制
private handleExceed(files: any, fileList: any[]) {
this.$message.warning('每次只能上传一个文件');
}
</script>
Vue+Elementui+Axios+TypeScript上传文件
最新推荐文章于 2024-12-06 17:27:42 发布