這是《基於nuxt和iview搭建OM後臺管理系統實踐》這一個系列文章的目錄,大體思路以下:vue
上一篇記錄了quill富文本的封裝過程,這一篇開始講解上傳組件(七牛、阿里雲oss)的封裝。ios
如動圖所示,爲上傳組件演示,能夠看到組件有上傳、預覽、刪除從新上傳、文件大小校驗等功能。 axios
實現原理:用input[type='file']標籤,並綁定一個change事件實現選擇本地電腦文件操做,同時經過其餘button觸發input的change事件,最終與阿里oss進行交互實現上傳圖片的功能。後端
步驟1:引入阿里雲osssdk代碼,須要注意的是:框架使用的nuxt,引入sdk須要按照nuxt的規範在head方法裏引入,附上head方法使用文檔地址;api
// 文件 components/upload.vue
<template>
<!--省略業務代碼-->
</template>
<script>
export default {
head: {
script: [{ src: "http://gosspublic.alicdn.com/aliyun-oss-sdk.min.js" }]//引入sdk
},
<script>
<style>
/*省略樣式代碼*/
</style>
複製代碼
步驟2:獲取上傳token,後端提供接口,因token有時效性故每次上傳操做時需向後端請求;bash
// 文件 components/upload.vue
<template>
<!--省略業務代碼-->
</template>
<script>
import axios from "~/plugins/axios";
export default {
head: {
script: [{ src: "http://gosspublic.alicdn.com/aliyun-oss-sdk.min.js" }]//引入sdk
},
method:{
doUpload() {
const _this = this;
const urls = [];
this.loading = true;
axios.get("/api/m/common/oss/getproperties")
.then(res=>{
//向後端請求獲取oss token等信息
_this.ossKey.AccessKeyId = res.data.data.AccessKeyId;
_this.ossKey.AccessKeySecret = res.data.data.AccessKeySecret;
_this.ossKey.BucketName = res.data.data.BucketName;
_this.ossKey.SecurityToken = res.data.data.SecurityToken;
//與阿里oss交互,上傳文件到服務器並返回文件路徑
})
}
}
<script>
<style>
/*省略樣式代碼*/
</style>
複製代碼
步驟3:與阿里oss交互,上傳文件到服務器並返回文件路徑;服務器
//
postOss(){
const _this = this;
const client = new window.OSS.Wrapper({
region: _this.region,
accessKeyId: _this.ossKey.AccessKeyId,
accessKeySecret: _this.ossKey.AccessKeySecret,
stsToken: _this.ossKey.SecurityToken,
bucket: _this.ossKey.BucketName
});
_this.percentage = 0;
const files = document.getElementById(_this.id);
if(files.files[0].size > _this.limitSize){//對文件大小進行校驗超出彈出提示框
_this.$Notice.warning({
title: '舒適提示',
desc: '文件超出'+_this.limitSize/1024+'kb限制,請壓縮一下圖片再上傳'
});
_this.loading = false;
return false;
}
if (files.files) {
const fileLen = document.getElementById(_this.id).files;
let resultUpload = "";
for (let i = 0; i < fileLen.length; i++) {
const file = fileLen[i];
// 隨機命名
let random_name ="mapOm/" + random_string(6) + "_" + new Date().getTime() + "." + file.name.split(".").pop();
// 上傳
client.multipartUpload(random_name, file, {
progress: function*(percentage, cpt) {
// 上傳進度
_this.percentage = percentage;
}
})
.then(results => {
// 上傳完成
_this.loading = false;
_this.show = true;
const url = "" + results.name;
_this.url = url;
_this.$emit('uploadedUrl',results.name);//把url傳給父組件
})
.catch(err => {
_this.loading = false;
console.log(err);
});
}
}
}
複製代碼
步驟4:引用並使用組件;app
import uploadImg from '~/components/upload';//引入組件
<upload-img label="土壤溫度" id="soilTemperature"
@uploadedUrl="(url) => this.formItem.trend.soilTemperature = url"
@remove="() => this.formItem.trend.soilTemperature = ''">
</upload-img>
複製代碼
iview官方提供了一個上傳組件,可是不符合咱們實際需求,我查看了源碼並在此基礎上進行了二次封裝最終實現了需求。如今再回過頭去看寫的代碼發現有點亂,後續抽空會進行代碼優化。同時要吐槽下阿里oss文檔,都沒有一個demo讓開發者查看,顯得很不友好。框架
如下爲本系列的文章合集,在此列出便於查閱:運維