element-ui的Upload上传图片、文件封装

上传文件

<template>
	<el-upload
		action="#"
		list-type="picture-card"
		:file-list="fileList"
		accept=".jpg,.jpeg,.bmp,.png,.pdf,.doc,.docx,.xls,.xlsx" :
		before-upload="beforeUpload" 
		:http-request="uploadFile">
	</el-upload>
</template>
<script>
export default {
  name: 'Upload',
  props: {
	width: {
      type: Number,
      default: 0
    },
    height: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      fileList: []
    };
  },
  methods: {
  	beforeUpload(file) {
  	  if(file.type.indexOf('image') > -1) {
  	    return new Promise((resolve, reject) => {
	        if (file.size / 1024 / 1024 > 2) {
	          setTimeout(() => {
		         this.$message({
		          message: '文件大小限制为2M',
		          type: 'warning'
		        })
	          }, 0)
	          reject()
	        } else {
	          const _URL = window.URL || window.webkitURL
	          const img = new Image()
	          img.onload = () => {
	            if (img.width === this.width && img.height === this.height) {
	              resolve(true)
	            } else {
	              this.$message({
	                message: `图尺寸${this.width}*${this.height}px!请重新上传!`,
	                type: 'warning'
	              });
	              reject(false)
	            }
	          };
	          img.src = _URL.createObjectURL(new Blob([file]))
	        }
      	});
	  } else {
		if (file.size / 1024 / 1024 > 2) {
          setTimeout(() => {
	         this.$message({
	          message: '文件大小限制为2M',
	          type: 'warning'
	        })
          }, 0)
          return false
	    }
	  }
  	},
  	async uploadFile(file) {
      const formData = new FormData()
      if (file.file) {
        formData.append('file', file.file)
      }
      if (file.raw) {
        formData.append('file', file.raw)
      }
      const config = {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      }
      const data = await uploadFile(formData, config);
    }
  }
}
</script>

你可能感兴趣的:(Element-ui,elementui,vue.js,javascript,es6,上传)