Use Qiniu-JavaScript-SDK to upload files to seven cattle cloud storage

A, Qiniu-JavaScript-SDK Introduction

  Based on JS-SDK can easily upload files from the browser end to seven cattle cloud storage, and upload pictures after successful wealth of data processing operations.
  JS-SDK support H5 File API compatible browser, in a low version of the browser, the need for additional plug-ins such as plupload, JS-SDK provides a number of interfaces can be combined with plug-in to upload work.

  Qiniu-JavaScript-SDK for the client SDK, does not include  token generation to achieve, for safety, token we recommend getting from the server through the network, the generated code can refer to the specific document server SDK.

1, reference documentation

  Official API documentation: JavaScript SDK

  Based front-end JavaScript SDK source address seven cattle API development: https://github.com/qiniu/js-sdk

2, is introduced (NPM installed)

  NPM stands Node Package Manager, is a  NodeJS  package management and distribution tools, has become the standard published Node module (package) is unofficial.

$ npm install qiniu-js

 

Two, javascript project realization  

  Create seven cattle upload component: hsedu_mgr / src / components / chart / QiniuUpload.vue

  The following code integrates the upload progress bar, and prompts the upload is complete

<template>
  <div class="ft-plant-upload-button" :class="boxClass">
    <Button class="upload-btn" type="ghost" icon="ios-cloud-upload-outline" :disabled="percent > 0 && percent < 100" @click="zh_uploadFile">{{qiniuUploadDesc}}</Button>
    <div class="progress-wraper" v-if="showProgress">
      <div class="progress" v-if="percent > 0 && percent < 100">
        <div class="progress-bar" role="progressbar" aria-valuemin="0" aria-valuemax="100" :style="{width: percent+'%'}">
        </div>
      </div>
      <div class="precent" v-if="percent > 0 && percent < 100">
        {{percent || 0 }}%
      </div>
    </div>
    <div class="file-name" v-if="percent == 100">{{fileName}}</div>
    <input type="file" ref="evfile" @change="zh_uploadFile_change" style="display:none">
    <input type="hidden" :value="qiniuKey">
  </div>

</template>

<script>
  import * as qiniu from "qiniu-js"

  export default {
    name: "QiniuUpload",
    props: {   // 子组件的props选项
      qiniuUploadDesc: {
        type: String,
        default: '上传文件'
      },
      classroomUpload: {
        default: '未知classroom'
      },
      filetype: {
        type: String
      },
      showProgress: {
        type: Boolean,
        default: false
      },
      boxClass: {
        type: String,
        default: ''
      }
    },
    data(){
      return {
        queryInfo: {
          limit: 10,
          offset: 0,
        },
        token: "",
        qiniuKey: "",
        percent: 0,
        percentText: '',
        fileName: ''
      } 
    }, 
    Methods: { 
      httpGetList: function () {
         var Self = the this ;
         the this . $ HttpGet ( the this . $ HTTP, "Users / the DataController / getUploadToken", the this . $ TrimJson (self.queryInfo), function (RET) { 
          the console.log ( 'RET' , ret.token);
           return ret.token; 
        }); 
      }, 
      // select upload files 
      zh_uploadFile () {
         the this ; $ refs.evfile.click (). 
      }, 
      // select the file trigger events
      zh_uploadFile_change (evfile) {
         IF (evfile) {
           // rear acquired token 
          the this .getQiniuToken () the then (RES =>. { 
            the console.log ( 'RES' , RES);
             var uptoken = RES;
             var userNo = the this $. . sessionUser.fetch () userNo;
             var timestamp = Date.parse ( new new a Date ());    // timestamp 
            var file evfile.target.files = [0];      // Blob object file upload 
            the this .FileName = file .name;
             var Key = the this .filetype + '/' + the this .classroomUpload + '/ the U-' + userNo + 'T' + + + file.name.split timestamp ( '.') POP () '.';.       // the resource files uploaded name to set the main key, if the key is null or undefined, the resource file name will hash value as a resource name. 

            config the let = { 
              useCdnDomain: to true ,          // indicates whether cdn acceleration domain name, is a Boolean value, true indication, the default is false. 
              Region: qiniu.region.z1      // Upload domain region (z1 North China), when a null or undefined, the automatic analyzer uploads domain region 
            }; 

            the let putExtra = { 
              fname: "",           // File original file name 
              params: {} ,         // load custom variables: 'X: name': 'Sex' 
              mimeType: null       // limit upload file type, the file type indicates not limit is null; restriction type into the array: [ "image / png", " Image / JPEG "," Image / GIF "] 
            }; 

            // class instance is observable with a subscribe method 
            var observable = qiniu.upload (File, Key, uptoken, putExtra, config);
             var Subscription observable.subscribe = ( {    // Upload start 
              Next: (Result) => {
                 // receiving upload progress information, result is the total field with Object 
                @ loaded: uploaded size; size: total Upload information; percent: current upload progress 
                console.log (the Result);     //The form: {Total: {loaded: 1671168, size: 2.24926 million, Percent: 74.29856930723882}} 
                the this .percent = result.total.percent.toFixed (0 ); 
              }, 
              error: (errResult) => {
                 // upload errors after failure given 
                the console.log (errResult) 
              }, 
              Complete: (Result) => {
                 // information returned after the successful reception of 
                the console.log (Result);    // the form: {hash: "Fp5_DtYW4gHiPEBiXIjVsZ1TtmPc", key: "% TStC006TEyVY5lLIBt7Eg .jpg "} 
                the this .qiniuKey = result.data.key;
                 the this $ EMIT ( 'Key',. the this.qiniuKey)
              }
            })
          })
        }
      },
      getQiniuToken(){
        return new Promise((resolve, reject)=>{
          var self = this;
          this.$httpGet(this.$http, "users/dataController/getUploadToken", this.$trimJson(self.queryInfo), function (ret) {
            console.log('ret', ret.token);
            resolve(ret.token);
          });
        })

      }
    }
  }
</script>
<style lang="scss" scoped>
.ft-plant-upload-button {
  vertical-align: middle;
  .progress {
    width: 85px;
    height: 7px;
    vertical-align: middle;
    display: -webkit-inline-box;
    display: -ms-inline-flexbox;
    display: inline-flex;
    background: silver;
    -webkit-box-shadow: none !important;
    box-shadow: none !important;
    margin-left: 5px;
  }
}
.upload-btn {
  border: 1px solid #5084fe;
  padding: 5px 23px;
  outline: none;
  border-radius: 4px;
  cursor: pointer;
  background: #fff;
  color: #333;
}
.progress-wraper {
  display: inline-block;
}
.progress {
  width: 85px;
  height: 7px;
  vertical-align: middle;
  display: inline-flex;
  background:rgba(192,192,192,1);
  box-shadow: none!important;
  margin-left: 5px;
  .progress-bar {
    display: inline-block;
    background:rgba(80,132,254,1);
  }
}
.precent {
  display: inline-block;
  vertical-align: middle;
  margin-left: 3px;
}
.file-name {
  display: inline-block;
  vertical-align: middle;
  margin-left: 3px;
}
.add-courseware {
  padding-left: 15px;
}
</style>

 

2, the introduction of seven cattle upload component in the parent assembly

<div class="form-group row">
    <label for="qiniu" class="col-md-3 col-form-label">课件上传</label>
    <QiniuUpload filetype="courseware" :qiniuUploadDesc="'上传课件'" :classroomUpload="queryInfo.classroomno" :boxClass="'add-courseware'" :showProgress="true" @key="setKey">
      <template slot="uploadTitle">
      </template>
    </QiniuUpload>
  </div>

<script>
  import Breadcrumb from '../chart/Breadcrumb';
  import Select2 from '../chart/Select2';
  import Enums from '../chart/Enums';
  import Upload from "../chart/Upload";
  import AddEditMain from '../chart/AddEditMain';
  import QiniuUpload from '../chart/QiniuUpload';

  export default {
    name: 'AddClassroomCourseware',
    components: {
      'Breadcrumb': Breadcrumb,
      'Select2': Select2,
      'Enums': Enums,
      'Upload': Upload,
      'AddEditMain': AddEditMain,
      'QiniuUpload': QiniuUpload
    },
    // 代码略
</script>

 

  Properties props used to transfer subassembly. This splicing a more complex file name (key: file resource name).

 

Guess you like

Origin www.cnblogs.com/xiugeng/p/11356381.html