美文网首页
plUpload分片上传

plUpload分片上传

作者: 金桔柠檬加冰 | 来源:发表于2020-07-10 17:35 被阅读0次

    主页面

          <pl-upload ref='plupload' :api-url='apiUrl' :file-list="fileList" :limit="1" biz-type="trainModule"
                  :draggable="true" accept-files=".docx,.doc,.xlsx,.xls,.ppt,.pptx" 
                  @onchange="handleFileChange" >
                </pl-upload>
    

    多文件上传组件部分

    <template>
      <div class="upgradeUpload">
        <div class="el-upload-dragger" id='browseButton'><i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
        </div>
        <div v-if='fileRawList.length' class="upload-item">
          <div v-for='(item,index) in fileRawList' :key='index'>
            <div class="upload-status">
              <span class="overtext" style="width: 185px;"><i class="el-icon-document"
                  style="margin-right: 5px;"></i>{{ item.name }}</span>
              <div class="warning-text">
                <span class="item" v-if="item.status === -1">正在计算MD5</span>
                <span class="item" v-if="item.status === 1 && item.percent === 0">MD5计算完成,准备上传</span>
                <span class="item" v-if="item.status === 4" style="color: brown">
                  上传失败
                </span>
                <span class="item" v-if="item.status === 5" style="color: chartreuse"><i
                    class="el-icon-circle-check"></i></span>
                <span class="item"
                  v-if='item.status === 2 || item.status === 1 && item.percent > 0'>{{item.percent}}%</span>
                <i class="el-icon-close close-icon" @click="deleteFile(item)"></i>
              </div>
            </div>
            <div class="progress">
              <el-progress v-if="item.percent || item.percent === 0" :stroke-width="2" :percentage="item.percent"
                :v-if="item.status === 2 || item.status === 1 && item.percent > 0" />
            </div>
          </div>
          <!-- <div @click='uploadStart'>上传</div> -->
          <div style=" margin-top: 20px;">
            <el-button type='primary' @click='uploadStart' size='mini'>上传</el-button>
          </div>
    
        </div>
      </div>
    </template>
    <script>
      // plupload参数文档:http://www.phpin.net/tools/plupload/
      import FileMd5 from '@/factory/file-md5.js'
      export default {
        name: 'Plupload',
        head() {
          return {
            title: '多文件分片上传'
          }
        },
        props: {
          // 文件上传类型限制
          acceptFiles: {
            type: String,
            default: '.png,.jpg,.bmp,.doc,.docx,.xls,.xlsx,.pdf,.rar,.zip'
          },
          bizType: {
            type: String,
            default: ''
          },
          fileList: {
            type: Array,
            default: () => []
          },
          limit: {
            type: Number,
            default: 5
          }
        },
        data() {
          return {
            up: {},
            basicForm: {},
            fileRawList: [],
            uploading: false
          }
        },
        watch: {
          up(val) {
            this.fileRawList = this.fileList.concat(val.files)
          },
          acceptFiles(val) {
            this.up.refresh()
          }
        },
        mounted() {
          this.pluploadInit()
        },
        methods: {
          pluploadInit() {
            var that = this
            var uploader = new this.$plupload.Uploader({
              browse_button: 'browseButton',
              drop_element: 'browseButton',
              url: 'https://httpbin.org/post',
              // url: 'http://192.168.8.132:80/jaz/upload',
              chunk_size: '10MB',
              // headers: that.headers,
              multipart: true, // 为true时将以multipart/form-data
              auto_start: true,
              max_retries: 0, // 当发生plupload.HTTP_ERROR错误时的重试次数,为0时表示不重试
              multi_selection: false, // 是否可以在文件浏览对话框中选择多个文件
              filters: {
                mime_types: [
                  { extensions: that.acceptFiles.replace(/\./g, '') }
                ],
                prevent_duplicates: false, // 不允许选取重复文件
                max_file_size: '1024mb' // 最大只能上传400kb的文件
              },
              init: {
                BeforeUpload(up, file) {
                  console.log('1')
                  // 上传时的附加参数,以键/值对的形式传入
                  up.setOption('multipart_params', {
                    'size': file.size,
                    'md5': file.md5,
                    'bizType': that.bizType
                  })
                },
                FileFiltered(up, files) {
                  console.log(files, '2')
                  // up.start()
                },
                FilesAdded(up, files) {
                  that.fileRawList.push(...files)
                  if (that.fileRawList.length > that.limit) {
                    that.deleteFile(that.fileRawList[0])
                  }
                  files.forEach((f) => {
                    f.status = -1
                    FileMd5(f.getNative(), (e, md5) => {
                      f['md5'] = md5
                      f.status = 1
                    })
                  })
                },
                FilesRemoved(upp, files) {
                  that.uploading = false
                },
                FileUploaded(up, file, info) {
                  if (info.status === 200) {
                    console.log('FileUploaded', info, file, up)
                    const { path } = JSON.parse(info.response).data
                    file.url = path
                    that.up.refresh()
                    that.$emit('onChange', that.fileRawList)
                  }
                },
                UploadComplete(up, files) {
                  that.uploading = false
                },
                Error(up, args) {
                  that.$message({
                    type: 'error',
                    message: args.message
                  })
                  that.uploading = false
                }
              }
            })
            uploader.init()
            this.up = uploader
            // 自动上传
            // uploader.bind('FilesAdded', this.uploadStart)
          },
          deleteFile(row) {
            this.fileRawList.splice(this.fileRawList.indexOf(row), 1)
            var file = this.up.getFile(row.id)
            file && this.up.removeFile(file)
            // 删除接口
            // row.url && removeFile({ filePath: row.url }).then(res => {
            //   if (res.success) {
            //     this.$emit('onChange', this.fileRawList.filter(item => {
            //       return item.url
            //     }))
            //     return
            //   }
            //   this.$message.warning('删除文件出现异常,请与管理员联系!')
            // })
          },
          uploadStart() {
            console.log('上传')
            this.uploading = true
            this.up.start()
          }
        }
      }
    </script>
    <style>
      .upgradeUpload {
        width: 500px;
        height: 100%;
        margin: 100px auto;
      }
    
      .upload-item {
        width: 370px;
        height: 25px;
        line-height: 25px;
      }
    
      .upload-status {
        display: flex;
        justify-content: space-between;
        font-size: 14px;
        color: #606266;
        margin-top: 10px;
        padding: 0px 6px;
        border-radius: 4px;
      }
    
      .progress {
        position: relative;
      }
    
      .el-progress__text {
        display: none !important;
      }
    
      .warning-text {}
    
      .close-icon {
        display: none;
        line-height: 25px;
      }
    
      .upload-status:hover {
        background-color: #F5F7FA;
      }
    
      .upload-status:hover .close-icon {
        display: block;
      }
    
      .upload-status:hover .item {
        display: none;
      }
    
      .el-progress-bar {
        padding-right: 0 !important;
        margin-right: 0 !important;
      }
    </style>
    

    file-md5.js

    'use strict'
    import SparkMD5 from 'spark-md5'
    export default function (file, callback) {
      console.log(file.size, '分片处理')
      var blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice
      var chunkSize = 10485760 // Read in chunks of 2MB
      var chunks = Math.ceil(file.size / chunkSize)
      var currentChunk = 0
      var spark = new SparkMD5.ArrayBuffer()
      var fileReader = new FileReader()
    
      fileReader.onload = function (e) {
        console.log('read chunk nr', currentChunk + 1, 'of', chunks)
        spark.append(e.target.result) // Append array buffer
        currentChunk++
    
        if (currentChunk < chunks) {
          loadNext()
        } else {
          callback(null, spark.end())
          console.log('finished loading')
        }
      }
    
      fileReader.onerror = function () {
        callback('oops, something went wrong.')
      }
    
      function loadNext() {
        var start = currentChunk * chunkSize
        var end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize
    
        fileReader.readAsArrayBuffer(blobSlice.call(file, start, end))
      }
    
      loadNext()
    }
    

    效果图


    分片上传.png

    相关文章

      网友评论

          本文标题:plUpload分片上传

          本文链接:https://www.haomeiwen.com/subject/mzimcktx.html