1. 程式人生 > >Vue Element UI + OSS上傳檔案

Vue Element UI + OSS上傳檔案

  Element提供了upload上傳元件,可以檢視官網upload元件的詳細介紹;檢視upload元件的上傳原始碼upload/ajax,使用的是XHR物件上傳檔案。在專案實踐中,發現該上傳方法上傳大檔案時會出現問題,所以決定使用阿里雲物件儲存服務(Object Storage Service,簡稱OSS),OSS詳細介紹可以檢視官網,本文主要講解的是OSS上傳檔案的前端,後臺開發請檢視官網介紹,SDK Browser.js講解了前端如何進行上傳。

1、使用npm安裝SDK的開發包:

npm install ali-oss

2、OSS配置

let oss = require('ali-oss'
); let client= new OSS.Wrapper({ accessKeyId: 'your access key', accessKeySecret: 'your access secret', bucket: 'your bucket name', region: 'oss-cn-hangzhou' });

3、上傳檔案
  OSS上傳檔案分為上傳Buffer內容、上傳blob資料、分片上傳,此處展示分片上傳

let result = await client.multipartUpload('object-key', 'local-file', {
    progress: async function
(p) {
console.log('Progress: ' + p); } });

  js呼叫OSS上傳檔案已經沒有問題,但是我們需要實現公用上傳元件,Element UI已經實現了Upload上傳元件,包括上傳進度、異常處理、拖拽等;那我們還有必要重新開發一個像Upload一樣的元件嗎?通過檢視Upload元件的API發現有一個http-request屬性,http-request覆蓋預設的上傳行為,可以自定義上傳的實現;看到這個我就省了很多事,直接用OSS上傳覆蓋XHR上傳。程式碼如下:

<template>
  <div>
    <el-upload
:auto-upload="false" :action="uploadUrl" ref="upload" :before-upload="fnBeforeUpload" :on-success="fnUploadSuccess" :on-exceed="fnUploadExceed" :data="data_extra" :headers="uploadHeaders" :http-request="fnUploadRequest" drag :limit="files" :disabled="disabled" multiple>
<i class="el-icon-upload"></i> <div class="el-upload__text">將檔案拖到此處,或<em>點選上傳</em></div> <div slot="tip" class="el-upload__tip">上傳檔案大小不能超過 1G</div> </el-upload> </div> </template> <script> import UploadFileApi from '@/api/system/UploadFileApi' import * as util from 'utils/common' import OSS from 'ali-oss' export default { name: 'fileUpload', props: { data_extra: { type: Object, required: true }, accept: { type: Array, required: true } }, data () { return { uploadUrl: '', uploadFileLength: 0, uploadFileSuccess: 0, uploadFileNames: [], uploadFileName: [], fileList: [], files: 10, uploadHeaders: { authorization: '' }, disabled: false } }, methods: { /** * @description [fnUploadRequest 覆蓋預設的上傳行為,實現自定義上傳] * @author shanshuizinong * @param {object} option [上傳選項] * @return {null} [沒有返回] */ async fnUploadRequest (option) { try { let vm = this vm.disabled = true // 獲取OSS配置資訊 let uploadFileApi = new UploadFileApi() let ret = await uploadFileApi.fileOssParams() if (!(ret.data && ret.data.code === '0' && ret.data.data)) { throw new Error('獲取OSS引數失敗') } let ossData = JSON.parse(ret.data.data) let relativePath = ossData.relativePath let client = new OSS.Wrapper({ policy: ossData.policy, accessKeyId: ossData.accessid, accessKeySecret: ossData.accesssecret, bucket: ossData.bucket, signature: ossData.signature }) let file = option.file const point = file.name.lastIndexOf('.') let suffix = file.name.substr(point) let fileName = file.name.substr(0, point) let date = vm.$moment().format('YYYYMMDDHHmm') let fileNames = `${fileName}_${date}${suffix}` // 分片上傳檔案 ret = await client.multipartUpload(relativePath + fileNames, file, { progress: async function (p) { let e = {} e.percent = p * 100 option.onProgress(e) } }) console.log(ret) if (ret.res.statusCode === 200) { option.onSuccess(ret) return ret } else { vm.disabled = false option.onError('上傳失敗') } } catch (error) { console.error(error) this.disabled = false option.onError('上傳失敗') this.$error(error.message) } }, /** * @description [fnUploadSuccess 檔案上傳成功的函式] * @author shanshuizinong * @return {null} [沒有返回] */ async fnUploadSuccess () { // TODO } } } </script>

  檢視upload原始碼upload.vue知道httpRequest會有一個檔案上傳的option選項作為引數,upload/ajax原始碼中上傳進度、上傳成功、上傳失敗都是通過option呼叫其方法進行觸發。