12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394 |
- <template>
- <div>
- <el-upload action=""
- :multiple="false"
- :show-file-list="false"
- accept="image/jpeg,image/png"
- class="image-uploader"
- :on-exceed="handleExceed"
- :on-change="onFrontImgChange"
- :before-upload="beforeUpload">
- <el-button type="primary" style="width: 200px;" class="mt20">
- {{placeholder}}
- </el-button>
- </el-upload>
- </div>
- </template>
- <script>
- import SparkMD5 from 'spark-md5'
- import { uploadImg } from "@/components/httpServer/httpServer.js";
- import { compressImg } from "../util.js";
- export default {
- name: 'Upload',
- components: {},
- props: {
- placeholder:{
- type: String,
- default: "点击上传基准照片",
- },
- },
- data() {
- return {
- fileMd5:'',
- onupload: false,
- }
- },
- methods: {
- beforeUpload(file) {
- // 限制上传类型
- let fileExtensions = ".jpg"
- //限制的上限为20M
- const max20M = file.size / 1024 / 1024/20;
- if (!fileExtensions) {
- this.$message.error('上传文件类型只能是 .doc, .docx, .pdf 格式!');
- }
- if (max20M >1) {
- this.$message.error('上传文件大小不能超过 20MB!');
- }
- return fileExtensions && max20M;
- },
- handleExceed( event ){
- console.log('handleExceed', event)
- },
- onFrontImgChange:function(file, fileList){
- const _this = this //this指向问题
- var fileReader = new FileReader();
- var dataFile = file.raw;
- //console.log(file)
- let blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice
- var spark = new SparkMD5();
- fileReader.readAsBinaryString(dataFile)
- //异步执行函数
- fileReader.onload = function(e){
- spark.appendBinary(e.target.result);
- var md5 = spark.end()
- _this.fileMd5 = md5;
- if( !_this.onupload){
- console.log('start', _this.fileMd5)
- _this.onupload = true
- _this.handleUpload( md5, file.raw )
- }else{
- console.log("skip", _this.fileMd5 )
- }
- }
- },
- handleUpload( rand, file ) {
- let that = this
- // 100k
- compressImg( file, 100 ).then( nfile=>{
- console.log( "nfile", nfile)
- const formData = new FormData()
- formData.append('avatar', nfile )
- uploadImg( that.fileMd5, formData ).then( res=>{
- that.onupload = false
- if( res.code== 200){
- that.$emit('onFinish', res.data.url)
- }
- })
- } )
- }
- }
- }
- </script>
|