今天有個需求,把項目中上傳文件從后臺服務(wù)端搬到華為云OBS上,找了好多資料發(fā)現(xiàn)好多博主并沒寫用什么調(diào)用,而是把華為云文檔搬過來,特封裝了一個完成組件復(fù)用,下面話不多說直接上代碼
注釋:代碼中###是需要填寫自己東西的
<template>
<div class="upload-file">
<el-upload
multiple
action
:on-change="fileChange"
:before-upload="handleBeforeUpload"
:file-list="fileList"
:limit="limit"
:on-exceed="handleExceed"
:show-file-list="false"
:headers="headers"
class="upload-file-uploader"
ref="upload"
>
<!-- 上傳按鈕 -->
<el-button size="mini" type="primary">選取文件</el-button>
<!-- 上傳提示 -->
<div class="el-upload__tip" slot="tip" v-if="showTip">
請上傳
<template v-if="fileSize">
大小不超過 <b style="color: #f56c6c">{{ fileSize }}MB</b>
</template>
<template v-if="fileType">
格式為 <b style="color: #f56c6c">{{ fileType.join("/") }}</b>
</template>
的文件
</div>
</el-upload>
<!-- 文件列表 -->
<transition-group
class="upload-file-list el-upload-list el-upload-list--text"
name="el-fade-in-linear"
tag="ul"
>
<li
:key="file.url"
class="el-upload-list__item ele-upload-list__item-content"
v-for="(file, index) in fileList"
>
<el-link :href="file.url" :underline="false" target="_blank">
<span class="el-icon-document"> {{ file.name }} </span>
</el-link>
<div class="ele-upload-list__item-content-action">
<el-link :underline="false" @click="handleDelete(index)" type="danger"
>刪除</el-link
>
</div>
</li>
</transition-group>
</div>
</template>
<script>
import { uuid } from "vue-uuid";
import { getToken } from "@/utils/auth";
import ObsClient from "esdk-obs-browserjs/src/obs";
export default {
name: "FileUpload",
props: {
// 值
value: [String, Object, Array],
// 數(shù)量限制
limit: {
type: Number,
default: 5,
},
// 大小限制(MB)
fileSize: {
type: Number,
default: 5,
},
// 文件類型, 例如['png', 'jpg', 'jpeg']
fileType: {
type: Array,
default: () => ["doc", "xls", "ppt", "txt", "pdf"],
},
// 是否顯示提示
isShowTip: {
type: Boolean,
default: true,
},
},
data() {
return {
number: 0,
uploadList: [],
headers: {
Authorization: "Bearer " + getToken(),
},
fileList: [],
file: undefined,
};
},
watch: {
value: {
handler(val) {
if (val) {
let temp = 1;
// 首先將值轉(zhuǎn)為數(shù)組
const list = Array.isArray(val) ? val : this.value.split(",");
// 然后將數(shù)組轉(zhuǎn)為對象數(shù)組
this.fileList = list.map((item) => {
if (typeof item === "string") {
item = { name: item, url: item };
}
item.uid = item.uid || new Date().getTime() + temp++;
return item;
});
} else {
this.fileList = [];
return [];
}
},
deep: true,
immediate: true,
},
},
computed: {
// 是否顯示提示
showTip() {
return this.isShowTip && (this.fileType || this.fileSize);
},
},
methods: {
uploadObs() {},
fileChange(file, fileList) {
this.file = file;
},
// 上傳前校檢格式和大小
handleBeforeUpload(file) {
console.log(file);
let that = this;
// 校檢文件類型
if (this.fileType) {
let fileExtension = "";
if (file.name.lastIndexOf(".") > -1) {
fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
}
const isTypeOk = this.fileType.some((type) => {
if (file.type.indexOf(type) > -1) return true;
if (fileExtension && fileExtension.indexOf(type) > -1) return true;
return false;
});
if (!isTypeOk) {
this.$modal.msgError(
`文件格式不正確, 請上傳${this.fileType.join("/")}格式文件!`
);
return false;
}
}
// 校檢文件大小
if (this.fileSize) {
const isLt = file.size / 1024 / 1024 < this.fileSize;
if (!isLt) {
this.$modal.msgError(`上傳文件大小不能超過 ${this.fileSize} MB!`);
return false;
}
}
this.$modal.loading("正在上傳文件,請稍候...");
let uuids = uuid.v1() + Date.now();
// 創(chuàng)建ObsClient實例
var obsClient = new ObsClient({
access_key_id: "###########", // 你的ak
secret_access_key: "#########", // 你的sk
server: "https://####", // 你的endPoint 記得加入https://
});
obsClient.putObject(
{
Bucket: "####", // 桶名
Key: uuids, // 文件名 此處用的是uuid+ 時間戳
SourceFile: file, //流文件
},
function (err, result) {
if (err) {
console.error("Error-->" + err);
that.handleUploadError();
} else {
console.log("Status-->" + result.CommonMsg.Status);
console.log(12312312);
that.uploadList.push({
name: `${uuids}`, //名字自取 這里我用了uuid + 時間戳
url: `https://ye-shuo-ddb.obs.cn-east-3.myhuaweicloud.com/${uuids}`, // 因為訪問路徑OBS沒有給你返回需要自行拼接 拼接格式: https:// + 桶名 + endPoint + / + 上傳的文件路徑
});
that.fileList = that.fileList.concat(that.uploadList);
that.uploadList = [];
that.number = 0;
that.$emit("input", that.listToString(that.fileList));
that.$modal.closeLoading();
console.log(that.fileList);
}
}
);
this.number++;
return true;
},
// 文件個數(shù)超出
handleExceed() {
this.$modal.msgError(`上傳文件數(shù)量不能超過 ${this.limit} 個!`);
},
// 上傳失敗
handleUploadError(err) {
console.log(err);
this.$modal.msgError("上傳圖片失敗,請重試");
this.$modal.closeLoading();
},
// 刪除文件
handleDelete(index) {
this.fileList.splice(index, 1);
this.$emit("input", this.listToString(this.fileList));
},
// 獲取文件名稱
getFileName(name) {
return name;
},
// 對象轉(zhuǎn)成指定字符串分隔
listToString(list, separator) {
let strs = "";
separator = separator || ",";
for (let i in list) {
strs += list[i].url + separator;
}
return strs != "" ? strs.substr(0, strs.length - 1) : "";
},
},
};
</script>
<style scoped lang="scss">
.upload-file-uploader {
margin-bottom: 5px;
}
.upload-file-list .el-upload-list__item {
border: 1px solid #e4e7ed;
line-height: 2;
margin-bottom: 10px;
position: relative;
}
.upload-file-list .ele-upload-list__item-content {
display: flex;
justify-content: space-between;
align-items: center;
color: inherit;
}
.ele-upload-list__item-content-action .el-link {
margin-right: 10px;
}
</style>
以上代碼為封裝的組件代碼,需要引入父組件后調(diào)用配置
下面圖為組件調(diào)用,注冊跟引入就不用我多說了吧,不會的自行百度
其中需要npm 安裝 vue-uuid 命令如下
npm install --save vue-uuid
另需要安裝OBSnpm包
npm i esdk-obs-browserjs
注:華為云前端直接上傳的話會出現(xiàn)跨域報錯,把華為云OBS CORS跨域規(guī)則設(shè)置一下
我設(shè)置的規(guī)則全部打開了
訪問路徑?。?! 代碼中注釋也有寫
browserjs的sdk在上傳的回調(diào)中沒有返回文件訪問地址, 所以我們可以自己進(jìn)行拼接
‘https://’ + bucket + ‘.obs.cn-north-4.myhuaweicloud.com/’ + key
bucket是桶名, bucket后面的字符串是 endPoint, 一般endPoint是
https://obs.cn-north-4.myhuaweicloud.com
去掉https即可. 最后的key則是文件名, 或文件路徑+文件名文章來源:http://www.zghlxwxcb.cn/news/detail-454779.html
至此就可以上傳+訪問了,感謝小伙伴們的觀看,如果幫到了你,請給我點個贊吧 謝謝~筆芯
CSDN私信我,接私活文章來源地址http://www.zghlxwxcb.cn/news/detail-454779.html
到了這里,關(guān)于vue+el-upload(封裝華為云OBS上傳文件)前端直傳的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!