webuploader 파일 업로드 컴포넌트 개발 예

小云云
풀어 주다: 2018-02-02 13:28:24
원래의
3251명이 탐색했습니다.

최근 프로젝트에서는 대용량 파일을 분할해서 업로드하고 백엔드 fastdfs에 연결하기 위해 Baidu의 webuploader를 사용해야 했기 때문에 파일 업로드를 위한 이 작은 플러그인을 작성하기 시작했습니다. 단계는 매우 간단하지만, 또한 많은 것이 있습니다. 제가 추측할 수 있는 함정은 제가 개발한 vue webuploader의 파일 업로드 구성요소를 주로 소개하는 것입니다. 이제 여러분과 공유하고 참고할 수 있기를 바랍니다.

자세한 내용은 다음과 같습니다.

1. Encapsulation 컴포넌트

Baidu에서 제공하는 webuploader.js와 Uploader.swf를 소개합니다.

css 스타일을 컴포넌트에 직접 작성합니다.


<template>
 <p>
  <p id="list" class="uploader-list"></p>
  <p id="wrapper">
   <p class="uploader-container">
    <p :id="id" limitSize="1" :ext="ext"></p>
    <el-button style="margin-bottom:10px;float:left;" size="small" :loading="uploadLoading" type="success" @click="start">上传到服务器</el-button>
    <el-button style="margin-left: 20px;margin-bottom:10px;float:left;" :disabled="stopBtn" size="small" type="danger" @click="stop">暂停上传</el-button>
   </p>
  </p>
  <p class="el-upload__tip">{{tip}}</p>
  <p class="file-list">
   <ul class="el-upload-list el-upload-list--text">
    <li v-for="file in fileList" :class="[&#39;el-upload-list__item&#39;, &#39;is-&#39; + file.status]" :key="file">
     <a class="el-upload-list__item-name">
      <i class="el-icon-document"></i>{{file.name}}
     </a>
     <label class="el-upload-list__item-status-label">
      <i :class="{&#39;el-icon-upload-success&#39;: true,&#39;el-icon-circle-check&#39;: listType === &#39;text&#39;,
     &#39;el-icon-check&#39;: [&#39;picture-card&#39;, &#39;picture&#39;].indexOf(listType) > -1}"></i>
     </label>
     <i class="el-icon-close" @click="removeFile(file)"></i>
     <el-progress
      v-if="file.status === &#39;uploading&#39;"
      :type="listType === &#39;picture-card&#39; ? &#39;circle&#39; : &#39;line&#39;"
      :stroke-width="listType === &#39;picture-card&#39; ? 6 : 2"
      :percentage="file.percentage">
     </el-progress>
    </li>
   </ul>
  </p>
 </p>
</template>
<script>
 import &#39;../js/jquery.js&#39;
 import &#39;../js/webuploader.js&#39;
 import { Base64 } from &#39;js-base64&#39;
 import CryptoJS from &#39;crypto-js&#39;;

 export default{
  name: &#39;fileUpload&#39;,
  props: {
   id: {
    type: String,
    default: function(){
     return "filePicker";
    }
   },
   //上传提示
   tip: {
    type: String,
    default: function(){
     return "";
    }
   },
   //文件后缀名限制
   ext: {
    type: String,
    default: function(){
     return "jpg,jpeg,png,pdf,mp4,avi.mp3";
    }
   },
   //分片大小设置
   chunkSize: {
    type: Number,
    default: function(){
     return 2097152;
    }
   },
   //分片上传重试次数
   chunkRetry: {
    type: Number,
    default: function(){
     return 1;
    }
   },
   //是否自动上传
   auto: {
    type: Boolean,
    default: function(){
     return false;
    }
   },
   //上传文件大小限制
   sizeLimit: {
    type: Number,
    default: function(){
     return 209715200;
    }
   },
   //上传文件数量限制
   countLimit: {
    type: Number,
    default: function(){
     return 5;
    }
   }
  },
  data(){
   return{
    appId: AppConfig.appId,
    securityKey: AppConfig.securityKey,
    checkUrl: AppConfig.checkUrl,
    uploadUrl: AppConfig.uploadUrl,
    mergeUrl: AppConfig.mergeUrl,
    previewName: &#39;选择文件&#39;,
    wul_fileMd5: &#39;&#39;,
    wul_size: 0,
    wul_fileName: &#39;&#39;,
    wul_chunk: 0,
    wul_uploader: &#39;&#39;,
    fileList: [],
    listType: &#39;text&#39;,
    percentage: 0,
    fileObject: {
     uid: &#39;&#39;,
     name: &#39;&#39;,
     ext: &#39;&#39;,
     type: &#39;&#39;,
     status: &#39;&#39;,
     percentage: 0,
     url: &#39;&#39;
    },
    uploadLoading: false,
    stopBtn: true
   }
  },
  methods: {
   /**
    * 获取当前上传列表中的文件
    * @returns {Array|*}
    */
   getFileList: function(){
    return this.fileList;
   },
   //绑定事件
   wul_init: function() {
    //提示只能选择一个文件
    this.wul_uploader.on(&#39;filesQueued&#39;, function (files) {
     if (files.length > 1) {
      this.$message({
       message: &#39;请选择一张图片&#39;,
       type: &#39;error&#39;
      });
      for (var i = 0; i < files.length; i++) {
       this.wul_uploader.cancelFile(files[i]);
      }
      this.wul_uploader.reset();
      this.wul_fileMd5 = "";
      this.wul_size = 0;
      this.wul_fileName = "";
      this.wul_chunk = 0;  //当前切片数
     }else{
      if( this.fileList.length == this.countLimit ){
       this.$message({
        message: &#39;已经达到上传文件限制数量&#39;,
        type: &#39;error&#39;
       });
      }else{
       //此时往需要上传的文件列表中添加文件
       let file = {
        uid: Date.now() + this.tempIndex++,
        name: files[0].name,
        type: files[0].type,
        ext: files[0].ext,
        status: "ready",
        percentage: 0
       }
       this.fileObject = file;
       this.fileList.push(this.fileObject);
      }
     }
    }.bind(this));

    //文件校验格式和大小
    this.wul_uploader.on(&#39;error&#39;, function (type) {
      debugger
     if (type == &#39;Q_EXCEED_SIZE_LIMIT&#39;) {
      this.$message({
       message: &#39;文件超过指定大小&#39;,
       type: &#39;error&#39;
      });
     }
     if (type == &#39;Q_TYPE_DENIED&#39;) {
      this.$message({
       message: &#39;文件格式错误,请选择文件&#39;,
       type: &#39;error&#39;
      });
     }
     if (type == &#39;F_EXCEED_SIZE&#39;) {
      this.$message({
       message: "文件超过" + this.sizeLimit / 1024 / 1024 + "M",
       type: &#39;error&#39;
      });
     }
    }.bind(this));

    //上传进度
    this.wul_uploader.on(&#39;uploadProgress&#39;, function (file, percentage) {
     this.percentage = percentage * 100;
     this.fileObject.status = "uploading";
     this.fileObject.percentage = this.percentage;
     console.log(this.fileObject.percentage);
    }.bind(this));

    //每次切片上传完成之后的判断
    this.wul_uploader.on(&#39;uploadAccept&#39;, function (object, ret) {
     if (ret.responseCode != 0) {
      this.wul_uploader.cancelFile(this.wul_uploader.getFiles()[0].id);
     }
    });

    this.wul_uploader.on(&#39;uploadBeforeSend&#39;, function(object, data, headers) {
     console.log(data);
    });
   },

   option: function(key, val) {
    this.wul_uploader.option(key, val);
    var options = this.wul_uploader.options;
    this.wul_uploader.destroy();  //注销uploader
    this.wul_uploader = WebUploader.create(options);
    this.wul_init();
   },
   start: function(){
    if(this.wul_uploader.getFiles()[0] != null) {
     this.wul_uploader.upload(this.wul_uploader.getFiles()[0].id);
     this.uploadLoading = true;
     this.stopBtn = false;
    } else {
     this.$message({
      message: "请选择上传文件",
      type: &#39;error&#39;
     });
    }
   },
   stop: function(){
    this.wul_uploader.cancelFile(this.wul_uploader.getFiles()[0].id);
   },
   removeFile: function(file){
    this.fileList.splice(this.fileList.indexOf(file), 1);
   },
   change: function(){
    this.option(&#39;accept&#39;, {
     title: &#39;Images&#39;,
     extensions: &#39;gif,jpg,jpeg,bmp,png&#39;
    });
   }
  },
  mounted(){
   WebUploader.Uploader.register({
    "before-send-file": "beforeSendFile",
    "before-send": "beforeSend",
    "after-send-file": "afterSendFile",
   }, {
    beforeSendFile: function (file) {
     var deferred = WebUploader.Deferred();
     this.wul_uploader.md5File(file).then(function (val) {
      this.wul_fileMd5 = val;
      this.wul_size = file.size;
      this.wul_fileName = file.name;
      var timestamp = Date.parse(new Date()) / 1000;
      var signParam = "{chunkSize=" + this.chunkSize + ", fileMd5=" + this.wul_fileMd5 + ", size=" + this.wul_size + ", timestamp=" + timestamp + "}";
      var sign = Base64.encode(CryptoJS.HmacSHA1(signParam, this.securityKey));
      // 获取断点续传位置
      jQuery.ajax({
       type: "POST",
       // 测试
       url: this.checkUrl,
       data: {
        // 文件大小
        size: this.wul_size,
        // 文件唯一标记
        fileMd5: this.wul_fileMd5,
        // 切片大小
        chunkSize: this.chunkSize,
        // 签名
        sign: sign,
        // 应用分配id
        appId: this.appId,
        // 当前时间戳
        timestamp: timestamp

       },
       dataType: "json",
       // 上传失败
       error: function (XMLHttpRequest, textStatus, errorThrown) {
        this.$message({
         message: "上传失败...",
         type: &#39;error&#39;
        });
        this.uploadLoading = false;
        this.stopBtn = true;
       }.bind(this),
       success: function (response) {
        if (response.responseCode == 0) { // 切片获取成功
         this.wul_chunk = response.chunk;
         deferred.resolve();
        } else { // 切片获取失败,请求成功
         this.wul_uploader.cancelFile(file);  //取消文件上传
         this.$message({
          message: "切片检查失败,请联系管理员",
          type: &#39;error&#39;
         });
         deferred.resolve();
         this.uploadLoading = false;
         this.stopBtn = true;
        }
       }.bind(this)
      });
      return deferred.promise();
     }.bind(this));
     return deferred.promise();
    }.bind(this),
    beforeSend: function (block) {
     var deferred = WebUploader.Deferred();
     if (block.chunk < this.wul_chunk) {
      return deferred.reject();
     }
     this.wul_uploader.md5File(block.blob).then(function (chunkMd5) {
      var timestamp = Date.parse(new Date()) / 1000;
      var signParam = &#39;{chunk=&#39; + block.chunk + &#39;, chunkMd5=&#39; + chunkMd5 + &#39;, chunkSize=&#39; + this.chunkSize + &#39;, fileMd5=&#39; + this.wul_fileMd5 + &#39;, size=&#39; + this.wul_size + &#39;, timestamp=&#39; + timestamp + &#39;}&#39;;
      var signTemp = CryptoJS.HmacSHA1(signParam, this.securityKey);
      var sign = Base64.encode(signTemp);  //获取sign值
      this.wul_uploader.options.formData = {
       &#39;timestamp&#39;: timestamp,
       &#39;appId&#39;: this.appId,
       &#39;chunk&#39;: block.chunk,
       &#39;chunkSize&#39;: this.chunkSize,
       &#39;fileMd5&#39;: this.wul_fileMd5,
       &#39;chunkMd5&#39;: chunkMd5,
       &#39;size&#39;: this.wul_size,
       &#39;sign&#39;: sign
      };
      deferred.resolve();
     }.bind(this))
     return deferred.promise();
    }.bind(this),
    afterSendFile: function (file) {
     var timestamp = Date.parse(new Date()) / 1000;
     var signParam = "{chunkSize=" + this.chunkSize + ", fileMd5=" + this.wul_fileMd5 + ", fileName=" + file.name + ", size=" + this.wul_size + ", timestamp=" + timestamp + "}";
     var sign = Base64.encode(CryptoJS.HmacSHA1(signParam, this.securityKey));
     // 如果分块上传成功,则通知后台合并分块
     jQuery.ajax({
      type: "POST",
      url: this.mergeUrl,
      data: {
       appId: this.appId,
       fileMd5: this.wul_fileMd5,
       fileName: file.name,
       chunkSize: this.chunkSize,
       sign: sign,
       size: this.wul_size,
       timestamp: timestamp
      },
      success: function (response) {
       if (response.responseCode == 0) {
        this.fileObject.status = "success";
        this.fileObject.percentage = 100;
        this.fileObject.url = response.filePath;
       } else {
        this.fileObject.status = "exception";
        this.$message({
         message: "上传失败,失败原因:" + response.responseMsg,
         type: &#39;error&#39;
        });
       }
       this.uploadLoading = false;
       this.stopBtn = true;
       this.wul_uploader.reset();
       this.wul_fileMd5 = "";
       this.wul_size = 0;
       this.wul_fileName = "";
       this.wul_chunk = 0;  //当前切片数
      }.bind(this)
     });
    }.bind(this)
   });
   this.wul_uploader = WebUploader.create({
    // swf文件路径
    swf: &#39;../js/Uploader.swf&#39;,
    // 文件接收服务端。
    server: this.uploadUrl,
    // 定义选择按钮
    pick: {
     "id": "#" + this.id,
     "innerHTML": this.previewName
    },
    // 自动上传
    auto: this.auto,
    // 禁止浏览器打开文件
    disableGlobalDnd: true,
    // 添加截图功能
    paste: &#39;#wrapper&#39;,
    // 定义拖动面板
    dnd: &#39;#wrapper&#39;,
    // 分片上传
    chunked: true,
    // 分片大小为2M
    chunkSize: this.chunkSize,
    // 分片上传失败重试次数
    chunkRetry: this.chunkRetry,
    // 图片不做压缩
    compress: false,
    // 队列设置10个,为了选择多个文件的时候能提示
    fileNumLimit: 10,
    // 提前准备好下一个文件
    prepareNextFile: true,
    // 限制单个文件大小
    fileSingleSizeLimit: this.sizeLimit,
    //线程数
    threads : 1,
    // 限制格式
    accept: {
     title: "access",
     extensions: this.ext
    }
   });
   this.wul_init();
  }
 }
</script>
<style>
 /* ----------------Reset Css--------------------- */
 html, body, p, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre,
 a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp,
 small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li,
 fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td,
 article, aside, canvas, details, figcaption, figure, footer, header, hgroup, menu, nav, section, summary,
 time, mark, audio, video, input {
  margin: 0;
  padding: 0;
  border: none;
  outline: 0;
  font-size: 100%;
  font: inherit;
  vertical-align: baseline;
 }

 html, body, form, fieldset, p, p, h1, h2, h3, h4, h5, h6 {
  -webkit-text-size-adjust: none;
 }

 article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section {
  display: block;
 }

 body {
  font-family: arial, sans-serif;
 }

 ol, ul {
  list-style: none;
 }

 blockquote, q {
  quotes: none;
 }

 blockquote:before, blockquote:after, q:before, q:after {
  content: &#39;&#39;;
  content: none;
 }

 ins {
  text-decoration: none;
 }

 del {
  text-decoration: line-through;
 }

 table {
  border-collapse: collapse;
  border-spacing: 0;
 }

 /* ------------ */
 #wrapper {
  width: 100%;
  margin: 0 auto;
  height: 35px;
 }

 .img-preview {
  width: 160px;
  height: 90px;
  margin-top: 1em;
  border: 1px solid #ccc;
 }

 .cropper-wraper {
  position: relative;
 }

 .upload-btn {
  background: #ffffff;
  border: 1px solid #cfcfcf;
  color: #565656;
  padding: 10px 18px;
  display: inline-block;
  border-radius: 3px;
  margin-left: 10px;
  cursor: pointer;
  font-size: 14px;

  position: absolute;
  right: 1em;
  bottom: 2em;
 }
 .upload-btn:hover {
  background: #f0f0f0;
 }
 .uploader-container{
  width: 100%;
  font-size: 10px;
 }

 .webuploader-container {
  position: relative;
  width: 100px;
  height: 21px;
  float: left;
 }
 .webuploader-element-invisible {
  position: absolute !important;
  clip: rect(1px 1px 1px 1px); /* IE6, IE7 */
  clip: rect(1px,1px,1px,1px);
 }
 .webuploader-pick {
  position: relative;
  display: inline-block;
  cursor: pointer;
  background: #00b7ee;
  padding: 6px 15px;

  color: #fff;
  text-align: center;
  border-radius: 3px;
  overflow: hidden;
 }
 .webuploader-pick-hover {
  background: #00a2d4;
 }

 .webuploader-pick-disable {
  opacity: 0.6;
  pointer-events:none;
 }
 .file-list{
  width: 100%;
 }
</style>
로그인 후 복사

2 . 컴포넌트 내보내기


var fileUpload = require(&#39;./src/file_upload.vue&#39;);

module.exports = {
 fileUpload
}
로그인 후 복사

3. 데모 참조 방법


<template>
 <p>
  <el-card class="box-card">
   <fileUpload ref="fileUpload" :ext="ext" :countLimit="5" :tip="tip">aaa</fileUpload>
  </el-card>
 </p>
</template>
<script>
 import {fileUpload} from &#39;@/components/fileUpload/index.js&#39;
 export default{
  name: &#39;hello&#39;,
  components: {fileUpload},
  data(){
   return{
    fileList: [],
    ext: &#39;png,jpg,jpeg,mp3,mp4,pdf&#39;,
    tip: &#39;可上传png/jpg/jpeg/mp3/mp4/pdf,大小不超过200M&#39;
   }
  },
  created(){

  },
  methods: {
   getFileList: function(){
    this.fileList = this.$refs.fileUpload.getFileList();
    console.log(this.fileList);
   }
  }
 }
</script>
로그인 후 복사

4. 작업 렌더링

관련 추천:

자세한 설명 Bootstrap 파일 입력 파일 업로드 구성 요소의 예

Fine Uploader 파일 업로드 구성 요소 응용 프로그램 소개_PHP 튜토리얼

vue Alibaba Cloud 업로드 구성 요소 자세한 설명

위 내용은 webuploader 파일 업로드 컴포넌트 개발 예의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!