前端直传文件到aliyun OSS

<template>
  <div id="container">
      <div class="img-item m-1 upload-file" id="selectfiles" @click="axioSignal">
        <span class="mask"></span>
        <b-form-file multiple accept="image/*"></b-form-file>
      </div>
  </div>
</template>

<script>
import plupload from 'plupload'

export default {
  name: 'formImg',
  data () {
    return {
      signal: {
        policyBase64: '',
        accessid: '',
        signature: ''
      },
      imgs: [],
      imgUrl: [],
      uploader: {}
    }
  },
  mounted () {
    let _this = this
    this.uploader = new plupload.Uploader({
      runtimes: 'html5,flash,silverlight,html4',
      browse_button: 'selectfiles',
      container: document.getElementById('container'),

      init: {
        PostInit: function () {
          console.log(`PostInit`)
          // _this.axioSignal()
          // console.log(_this.onImgs)
          // _this.imgs.push(_this.onImgs)
          // _this.imgs = _this.onImgs
          // console.log(_this.onImgs)
          // console.log(_this.imgs)
        },

        FilesAdded: function (up, files) {
          _this.uploader.start()
          // plupload.each(files, function (file) {
          console.log(`FilesAdded`)
          // })
        },

        BeforeUpload: function (up, file) {
          _this.set_upload_param(up, file.name, true)
        },

        // UploadProgress: function (up, file) {
        //   console.log(`UploadProgress`)
        // },

        FileUploaded: function (up, file, info) {
          console.log(`FileUploaded`)
          if (info.status === 200) {
            _this.imgUrl.forEach(item => {
              _this.imgs.push(item)
              _this.imgUrl = []
            })
            _this.$emit('imgs', _this.imgs)
          }
        }

        // Error: function (up, err) {
        //   document.getElementById('console').appendChild(document.createTextNode('
Error xml:' + err.response))
        // }
      }
    })
    // _this.uploader.addFileFilter('max_file_size', function (maxSize, file, cb) {
    //   var undef
    //
    //   maxSize = plupload.parseSize(maxSize)
    //
    //   // Invalid file size
    //   if (file.size !== undef && maxSize && file.size > maxSize) {
    //     this.trigger('Error', {
    //       code: plupload.FILE_SIZE_ERROR,
    //       message: plupload.translate('File size error.'),
    //       file: file
    //     })
    //     cb(false)
    //   } else {
    //     cb(true)
    //   }
    // })
    _this.uploader.init()
  },
  methods: {
    axioSignal () {
      console.log(`axioSignal`)
      this.$axios({
        method: 'get',
        url: 'http://www.lyly360.com/fs/ali/signal'
      }).then(res => {
        this.signal.policyBase64 = res.policy
        this.signal.accessid = res.accessid
        this.signal.signature = res.signature
        this.signal.host = res.host
      })
    },
    formatNames (files) {
      console.log(`formatNames`)
      if (files.length === 1) {
        return files[0].name
      } else {
        return `${files.length} files selected`
      }
    },
    // postfiles () {
    //   this.uploader.start()
    // },
    random_string (len) {
      len = len || 32
      var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
      var maxPos = chars.length
      var pwd = ''
      for (var i = 0; i < len; i++) {
        pwd += chars.charAt(Math.floor(Math.random() * maxPos))
      }
      return pwd
    },

    get_suffix (filename) {
      var pos = filename.lastIndexOf('.')
      var suffix = ''
      if (pos !== -1) {
        suffix = filename.substring(pos)
      }
      return suffix
    },

    calculate_object_name (filename) {
      var suffix = this.get_suffix(filename)
      var randName = this.random_string(10) + suffix
      return randName
    },

    set_upload_param (up, filename) {
      var randFileName = 'file' + this.calculate_object_name(filename)
      this.imgUrl.push(this.signal.host + '/' + randFileName + '-ly.jpg')
      var newMparams = {
        'key': randFileName,
        'policy': this.signal.policyBase64,
        'OSSAccessKeyId': this.signal.accessid,
        'success_action_status': '200',
        'signature': this.signal.signature
      }

      up.setOption({
        'url': this.signal.host,
        'multipart_params': newMparams
      })
    }
  }
}
</script>

<style lang="stylus" scoped>
  .upload-file {
    height: 100px;
     100px;
    vertical-align: middle;
    text-align: center;
    line-height: 100px;
  }
  .upload-file .custom-file {
    height: 100px;
     100px;
    opacity: 0;
  }
  >>>.upload-file .custom-file input {
    height: 80%;
     80%;
    overflow hidden
  }
  .mask {
    position: absolute;
     100%;
    height: 100%;
    background-image: url(../assets/upload.png);
    background-size: 100px 100px;
    background-position: center center
    left: 0;
    top: 0;
  }

</style>

原文地址:https://www.cnblogs.com/izhaong/p/12154290.html