oss上傳-以及阿里后臺(tái)配置

準(zhǔn)備前

后臺(tái)項(xiàng)目:
后臺(tái)項(xiàng)目用的 vue+餓了么ui 框架
效果:

image.png

1.下載oss 插件

npm install ali-oss
  1. 封裝client.js文件:
const OSS = require('ali-oss');
export default function client() {
  var client = new OSS({
    region: 'oss-cn-guangzhou', // OSS所在的地域
    accessKeyId: 'LTAI5tQ*******iXBYoWM', // 訪問密鑰ID
    accessKeySecret: 'kpdSXYF**************w4X8uqsGA5', // 訪問密鑰Secret
    bucket: 'jwlc', // 存儲(chǔ)桶(Bucket)的名稱
  })  //后端提供數(shù)據(jù)
  return client
}
  1. 封裝uploadOss.vue組件
<template>
    <div class="upload-file">
        <el-upload class="upload-demo" :drag="isDrag" ref="uploadItem" action="" :before-upload="beforeVideoUpload"
            :show-file-list="false" :http-request="Upload">
            <el-button v-if="!isDrag" size="small" type="primary">點(diǎn)擊上傳</el-button>
            <template v-else>
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">將文件拖到此處匹涮,或<em>點(diǎn)擊上傳</em></div>
            </template>
            <div class="el-upload__tip" slot="tip">
                請(qǐng)上傳
                <template v-if="fileSize"> 大小不超過 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
                <template v-if="fileType"> 格式為 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>
                的文件
                <template v-if="limit">蛉抓,最多上傳{{ limit }}個(gè)附件</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.currentUrl" :underline="false" target="_blank">
                    <span class="el-icon-document"> {{ getFileName(file.name) }} </span>
                </el-link>
                <div class="ele-upload-list__item-content-action">
                    <el-link :href="file.currentUrl" :underline="false" target="_blank" type="primary">下載</el-link>
                    <el-link :underline="false" @click="handleDelete(index)" type="danger">刪除</el-link>
                </div>
            </li>
        </transition-group>
    </div>
</template>

<script>
import client from "./client.js"

export default {
    name: 'Upload-oss',
    props: {
        // 值
        value: [String, Object, Array],
        // 數(shù)量限制
        limit: {
            type: Number,
            default: 5,
        },
        // 大小限制(MB)
        fileSize: {
            type: Number,
            default: 5,
        },
        // 文件類型, 例如['png', 'jpg', 'jpeg']
        fileType: {
            type: Array,
            // default: () => ['txt', 'doc', 'docx', 'pdf', 'jpeg', 'png', 'xls', 'xlsx', 'ppt', 'pptx'],
            default: null,
        },
        isDrag: {
            type: Boolean,
            default: true
        }
    },
    watch: {
        value: {
            handler(val) {
                if (val) {
                    let temp = 1;
                    // 首先將值轉(zhuǎn)為數(shù)組
                    const list = Array.isArray(val) 
                        ? val : Object.prototype.toString.call(val) == '[object Object]' 
                        ? [val] : this.value.split(',');
                    // 然后將數(shù)組轉(zhuǎn)為對(duì)象數(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
        }
    },
    data() {
        return {
            videoUploadPercent: 0, // 上傳進(jìn)度
            fileList: [],
        }
    },
    async mounted() {
        // 測(cè)試
        const testUrl = '/test/2024/12/10/1733812864000.png'
        const course = await client().get(testUrl)
        console.log('course', course);
        if (course.res) {
            const sourceUrl = this.getUrl(course.res.data, course.res.headers['content-type'])
            console.log('sourceUrl', sourceUrl);
        }
    },
    methods: {
        getUrl(binaryData, fileType) {
            if (!binaryData) return ''
            const blob = new Blob([binaryData], { type: fileType });
            const sourceUrl = URL.createObjectURL(blob);
            return sourceUrl;
        },
        Upload(file) {
            console.log('Upload', file, file.file)
            const fileEndName = file.file.name
            const date = new Date()
            const year = date.getFullYear()
            const month = String(date.getMonth() + 1).padStart(2, '0')
            const day = String(date.getDate()).padStart(2, '0')
            const formattedDate = `${year}/${month}/${day}/`;
            const fileName = '/test/' + formattedDate +
                `${Date.parse(new Date())}_` +
                fileEndName //定義唯一的文件名

            // client().put(fileName, file.file)
            // 大文件上傳
            client()
                .multipartUpload(fileName, file.file, {
                    progress: (p) => {
                        //獲取進(jìn)度條的值
                        this.videoUploadPercent = Math.floor(p * 100)
                    }
                })
                .then(async (result) => {
                    console.log('result', result);
                    // const sourceUrl = this.getUrl(course.res.data, file.file.type)
                    // this.fileList.push({
                    //     name: fileEndName,
                    //     url: result.name,
                    // })
                    // console.log('sourceUrl', sourceUrl, this.fileList);
                    const course = await client().get(result.name)
                    if (course.res) {
                        const sourceUrl = this.getUrl(course.res.data, course.res.headers['content-type'])
                        this.fileList.push({
                            name: fileEndName,
                            url: result.name,
                            currentUrl: sourceUrl
                        })
                        this.$emit("input", this.fileList);
                        console.log('sourceUrl', sourceUrl, this.fileList);
                    }
                })
                .catch(err => {
                    console.log('oss err:', err);
                })
        },
        //上傳視頻前
        beforeVideoUpload(file) {
            const isLt10M = file.size / 1024 / 1024 < 80
            // 校檢文件類型
            if (this.fileType) {
                const fileName = file.name.split('.');
                const fileExt = fileName[fileName.length - 1];
                const isTypeOk = this.fileType.indexOf(fileExt) >= 0;
                if (!isTypeOk) {
                    this.$modal.msgError(`文件格式不正確, 請(qǐng)上傳${this.fileType.join("/")}格式文件!`);
                    return false;
                }
            }
            if (!isLt10M) {
                this.$modal.msgError('上傳視頻大小不能超過80MB哦!')
                return false
            }
            return true
        },

        // 刪除文件
        handleDelete(index) {
            this.fileList.splice(index, 1);
            this.$emit("input", this.fileList);
        },
        // 獲取文件名稱
        getFileName(name) {
            if (!name) return ''
            // 如果是url那么取最后的名字 如果不是直接返回
            if (name.lastIndexOf("/") > -1) {
                return name.slice(name.lastIndexOf("/") + 1);
            } else {
                return name;
            }
        },
        clearAll() {
            this.fileList = []
        }
    }
}
</script>

<style lang="scss" scoped>
.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;
}

.upload-demo {
    width: 100%;
}

.el-icon-document {
    margin-left: 8px;
}

::v-deep .el-upload,
::v-deep .el-upload-dragger {
    width: 100%;
}
</style>
  1. 頁面上引入組件
<el-dialog title="oss文件上傳" :visible.sync="isShow" width="500px" append-to-body>
      <uploadOss v-model="fileList"></uploadOss>
</el-dialog>

阿里控制臺(tái)配置

  1. 創(chuàng)建Bucket


    image.png

2.添加RAM 用戶賬號(hào)權(quán)限


image.png

2.1 oss權(quán)限全選添加


image.png
  1. 允許跨域


    image.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末甩骏,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌笑窜,老刑警劉巖笼痹,帶你破解...
    沈念sama閱讀 222,252評(píng)論 6 516
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異憔狞,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)彰阴,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,886評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門瘾敢,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人尿这,你說我怎么就攤上這事簇抵。” “怎么了射众?”我有些...
    開封第一講書人閱讀 168,814評(píng)論 0 361
  • 文/不壞的土叔 我叫張陵碟摆,是天一觀的道長。 經(jīng)常有香客問我责球,道長焦履,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,869評(píng)論 1 299
  • 正文 為了忘掉前任雏逾,我火速辦了婚禮嘉裤,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘栖博。我一直安慰自己屑宠,他們只是感情好怀大,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,888評(píng)論 6 398
  • 文/花漫 我一把揭開白布耕肩。 她就那樣靜靜地躺著蜈膨,像睡著了一般鳞芙。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上卫玖,一...
    開封第一講書人閱讀 52,475評(píng)論 1 312
  • 那天公你,我揣著相機(jī)與錄音,去河邊找鬼假瞬。 笑死陕靠,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的脱茉。 我是一名探鬼主播剪芥,決...
    沈念sama閱讀 41,010評(píng)論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼琴许!你這毒婦竟也來了税肪?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,924評(píng)論 0 277
  • 序言:老撾萬榮一對(duì)情侶失蹤榜田,失蹤者是張志新(化名)和其女友劉穎益兄,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體串慰,經(jīng)...
    沈念sama閱讀 46,469評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡偏塞,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,552評(píng)論 3 342
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了邦鲫。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,680評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡神汹,死狀恐怖庆捺,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情屁魏,我是刑警寧澤滔以,帶...
    沈念sama閱讀 36,362評(píng)論 5 351
  • 正文 年R本政府宣布,位于F島的核電站氓拼,受9級(jí)特大地震影響你画,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜桃漾,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,037評(píng)論 3 335
  • 文/蒙蒙 一坏匪、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧撬统,春花似錦适滓、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,519評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽罚屋。三九已至,卻和暖如春嗅绸,著一層夾襖步出監(jiān)牢的瞬間脾猛,已是汗流浹背鱼鸠。 一陣腳步聲響...
    開封第一講書人閱讀 33,621評(píng)論 1 274
  • 我被黑心中介騙來泰國打工漆弄, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留撼唾,地道東北人倒谷。 一個(gè)月前我還...
    沈念sama閱讀 49,099評(píng)論 3 378
  • 正文 我出身青樓深夯,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子掌呜,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,691評(píng)論 2 361

推薦閱讀更多精彩內(nèi)容