1. 程式人生 > >cordova下載-cordova-plugin -file-transfer-vue案例

cordova下載-cordova-plugin -file-transfer-vue案例

安裝

cordova plugin add cordova-plugin-file-transfer

程式碼

專案中使用的ui框架是mint-ui,功能包括:下載檔案,進度條

HTML:

    <mt-button @click="createFilePath" class="phone"><img src="@/assets/images/app-center/icon-phone.png" slot="icon">下載到手機</mt-button>
    <!-- 展示進度條 -->
    <mt-popup class="isProgress" v-model="isProgress" position="center" :closeOnClickModal="false">
      <div class="m-progress">
        <div class="tip">正在下載中({{progress}}%)...</div>
        <mt-progress class="mt-progress" :value="progress" :bar-height="10">
        </mt-progress>
      </div>
      <button class="cancel" @click="cancelDownload">取消</button>
    </mt-popup>

JS:

  mounted() {
    this.initialize();
  },
    data() {
    return {
      // 裝置準備
      ready: false,
      // 進度條
      progress: null,
      // 顯示進度條
      isProgress: false,
      //下載物件
      fileTransfer: null,
      // 下載地址
      downloadUrl: null,
      //預覽資料
      previewData: {
		title:'1_michael_ouyang',
		extension:'jpg',
		file_url:'http://avatar.csdn.net/7/E/0/1_michael_ouyang.jpg'
	},
},
 methods: {
    initialize() {
      document.addEventListener(
        'deviceready',
        this.onDeviceReady.bind(this),
        false
      );
    },
    // deviceready Event Handler
    onDeviceReady() {
      this.ready = true;
    },

    // 建立檔案路徑
    createFilePath() {
      let _this = this;
      if (_this.ready) {
        window.requestFileSystem(
          LocalFileSystem.PERSISTENT,
          0,
          function(fs) {
            fs.root.getFile(
              _this.previewData.title + '.' + _this.previewData.extension,//下載檔名稱 例:1_michael_ouyang.jpg
              { create: true, exclusive: false },
              function(fileEntry) {
                //呼叫fileTransfer外掛,下載圖片
                _this.isProgress = true;
                _this.downLoadFile(fileEntry.nativeURL);
              },
              function(err) {
                console.log('err', err);
                _this.toast('下載失敗,請稍後重試');
              }
            );
          },
          function(error) {
            console.log('error', error);
            _this.toast('下載失敗,請稍後重試');
          }
        );
      } else {
        _this.toast('下載失敗,請稍後重試');
      }
    },
    // fileTransfer plugin
    downLoadFile(fileURL) {
      let _this = this;
      _this.progress = 0;
      // 初始化FileTransfer物件
      _this.fileTransfer = new FileTransfer();
      // 伺服器下載地址
      let uri = encodeURI(_this.previewData.file_url);
      //監聽下載進度
      _this.fileTransfer.onprogress = function(e) {
        if (e.lengthComputable) {
          const progress = e.loaded / e.total;
          _this.progress = (progress * 100).toFixed(2);
        }
      };
      // 呼叫download方法
      _this.fileTransfer.download(
        uri, //uri網路下載路徑
        fileURL, //url本地儲存路徑
        function(entry) {
          // 手機儲存地址
          _this.downloadUrl = decodeURIComponent(entry.toURL());
          if (_this.progress > 1 || _this.progress === 1) {
            _this.isProgress = false;
            // MessageBox('提示', '下載已完成,檔案儲存在: ' + _this.downloadUrl);
            MessageBox('下載已完成', '檔案儲存在手機根目錄 ');
            _this.addDownRecord();
          }
        },
        function(error) {
          console.log('download error source ' + error.source);
          console.log('download error target ' + error.target);
          console.log('upload error code' + error.code);
        }
      );
    },
    /**
     * desc:取消下載
     */
    cancelDownload() {
      MessageBox.confirm('確定取消嗎?').then(action => {
        if (this.isProgress) {
          this.isProgress = false;
          this.fileTransfer.abort();
          this.fileTransfer = null;
          this.progress = 0;
        }
      });
    }
  }

CSS:

/* 下載進度 */
.isProgress {
  width: 85%;
  height: 2.86rem;
  border-radius: 0.2rem;
  .m-progress {
    padding: 0.5rem 0.5rem 0;
    height: 55%;
    .tip {
      font-size: 0.28rem;
      margin-bottom: 0.25rem;
    }
  }
  .cancel {
    width: 100%;
    line-height: 3.5;
    text-align: center;
    border-radius: 0.2rem;
    border-top: 0.01rem solid #f0f0f0;
  }
}