VUE 實(shí)現(xiàn)element upload上傳圖片到阿里云
首先安裝依賴
cnpm install ali-oss
封裝client

若是想減小打包后靜態(tài)資源大小,可在index.html引入:(然后在client.js里注釋掉const OSS = require(‘a(chǎn)li-oss'))
<script src="http://gosspublic.alicdn.com/aliyun-oss-sdk-4.4.4.min.js"></script>
const OSS = require('ali-oss')
export function client(data) {
// 后端提供數(shù)據(jù)
return new OSS({
region: data.endpoint, // *****.aliyuncs.com
accessKeyId: data.accessKeyId,
accessKeySecret: data.accessKeySecret,
bucket: data.bucketName,
endpoint: data.endpoint,
secure: true
})
}
然后,在vue頁面引用,給client傳入后臺(tái)返回的阿里數(shù)據(jù)
結(jié)果如下圖:

1、HTML部分
<el-upload action="" :http-request="Upload" :data="Aliyun" :multiple="false" :show-file-list="true" list-type="picture-card" :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :limit="5" > <i class="el-icon-plus" /> </el-upload> <el-dialog :visible.sync="dialogVisible"> <img width="100%" :src="dialogImageUrl" alt=""> </el-dialog> <p style="color: #999;">圖片上傳限制: 1.最多5張; 2.最大1M</p>
2、JS部分
import { getAliyun, createOrder } from '@/api/order-management'
import { client } from '@/utils/alioss'
export default {
name: 'Appeal',
data() {
return {
dialogImageUrl: '',
dialogVisible: false,
Aliyun: {}, // 存簽名信息
progress: 0, // 進(jìn)度條
imgUrl: [] // 存上傳后的圖片url
}
},
created() {
this.getAliyun()
},
methods: {
// 獲取阿里云數(shù)據(jù)
async getAliyun() {
const { data } = await getAliyun()
this.Aliyun = data
},
// 上傳圖片
Upload(file) {
const that = this
// 判斷擴(kuò)展名
const tmpcnt = file.file.name.lastIndexOf('.')
const exname = file.file.name.substring(tmpcnt + 1)
const names = ['jpg', 'jpeg', 'png']
if (names.indexOf(exname) < 0) {
this.$message.error('不支持的格式!')
return
}
if (file.size > 1024 * 1024) {
this.$message.error('圖片大小最大1M')
return
}
async function multipartUpload() {
// const fileName = that.name + file.file.uid
const fileName = that.Aliyun.objectName + +'/' + Date.now() + '-' + file.file.name
// fileName = aliyunConfig.objectName+'/'+Date.now()+'-'+file.name //所要上傳的文件名拼接 (test/)
// 定義唯一的文件名,打印出來的uid其實(shí)就是時(shí)間戳
// client 是第一步中的 client
client(that.Aliyun).put(fileName, file.file,
{
progress: function(p) { // 獲取進(jìn)度條的值
console.log(p)
that.progress = p * 100
}
}).then(
result => {
// 下面是如果對(duì)返回結(jié)果再進(jìn)行處理,根據(jù)項(xiàng)目需要
// console.log(result)
// that.imgUrl = 'http://' + result.bucket + '.' + that.Aliyun.endpoint + '/' + result.name
that.dialogImageUrl = result.url
that.imgUrl.push({
name: file.file.name,
url: result.url
})
console.log(that.imgUrl)
}).catch(err => {
console.log('err:', err)
})
}
multipartUpload()
},
// 圖片預(yù)覽
handlePictureCardPreview(file) {
this.dialogImageUrl = file.url
this.dialogVisible = true
},
// 刪除圖片
handleRemove(file, fileList) {
// console.log(file)
for (var i in this.imgUrl) {
if (this.imgUrl[i].name === file.name) {
this.imgUrl.splice(i, 1)
}
}
}
}
}
</script>
補(bǔ)充知識(shí):vue-cli項(xiàng)目中,配合element_ui來實(shí)現(xiàn)上傳圖片與視頻到oss上。
<template>
<div class="basicInfo">
<el-upload class="avatar-content"
v-loading="fileLoading"
accept="image/*"
drag action="https://zxcity-app.oss-cn-hangzhou.aliyuncs.com"
:show-file-list="false"
:data="ossParams"
:before-upload="checkParams"
:on-progress="progress"
:on-error="uploadErr"
:on-success="uploadSuccess"
:on-remove="fileListRemove"
multiple
>
</el-upload>
<div v-for="(item,index) in fileList" :key="index" class="imgDiv">
<img :src="item.imgUrl" alt="">
<p>{{item.progress}}</p>
</div>
</div>
</template>
<script>
import axios from 'axios'
export default {
data () {
return {
form: {
url: ''
},
fileList: [],
fileLoading: false,
ossParams: {
expireTime: '',
key: '',
dir: ''
}
}
},
methods: {
// 圖片上傳前檢測參數(shù)變化
checkParams (file) {
var _this = this
var promise = new Promise((resolve, reject) => {
axios.get('https://share.zxtest.izxcs.com/zxcity_restful/ws/oss/ossUpload', {})
.then(function (response) {
var params = response.data
_this.ossParams = params
_this.ossParams.name = file.name
_this.ossParams.OSSAccessKeyId = params.accessid
_this.ossParams.success_action_status = '200'
_this.ossParams.key = params.dir + '/' + _this.getUUID()
var obj = {
name: _this.ossParams.name,
key: _this.ossParams.key,
host: _this.ossParams.host,
progress: 0,
imgUrl: ''
}
_this.fileList.push(obj)
// _this.fileLoading = true
resolve()
})
.catch(function (error) {
console.log(error, '錯(cuò)誤')
reject(error)
})
})
return promise
},
// 上傳中
progress (event, file, fileList) {
console.log('上傳中...')
console.log(file)
console.log(fileList)
this.fileList.forEach((item, index) => {
if (item.name === file.name) {
item.progress = parseInt(file.percentage)
}
})
},
// 上傳失敗提示
uploadErr (res) {
this.$message.error('上傳出錯(cuò)!')
},
// 上傳成功后上傳到file表
uploadSuccess (response, file, fileList) {
console.log('上傳成功')
this.fileList.forEach((item, index) => {
if (item.name === file.name) {
item.imgUrl = item.host + '/' + item.key
item.progress = 100
}
})
},
// 文件刪除
fileListRemove (file, fileList) {
this.form.url = ''
},
// 隨機(jī)名稱
getUUID () {
return `${this.str4()}${this.str4()}-${this.str4()}-${this.str4()}-${this.str4()}-${this.str4()}${this.str4()}${this.str4()}`
},
str4 () {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
}
}
}
</script>
<style lang="less" scoped>
.imgDiv{
display: block;
float: left;
width: 80px;
height: 100px;
border: 2px solid black;
img{
display: block;
width: 50px;
height: 80px;
}
p{
font-size: 14px;
text-align: center;
}
}
</style>
以上這篇VUE 實(shí)現(xiàn)element upload上傳圖片到阿里云就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
- element-ui中el-upload多文件一次性上傳的實(shí)現(xiàn)
- element-ui 中使用upload多文件上傳只請(qǐng)求一次接口
- Element-UI中Upload上傳文件前端緩存處理示例
- 用element的upload組件實(shí)現(xiàn)多圖片上傳和壓縮的示例代碼
- vue-cli3.0+element-ui上傳組件el-upload的使用
- element-ui upload組件多文件上傳的示例代碼
- element UI upload組件上傳附件格式限制方法
- 在vue項(xiàng)目中使用element-ui的Upload上傳組件的示例
- Element-ui upload上傳文件限制的解決方法
相關(guān)文章
Vue.js項(xiàng)目在IE11白屏報(bào)錯(cuò)的解決方法
本文主要介紹了Vue.js項(xiàng)目在IE11白屏報(bào)錯(cuò)的解決方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-08-08
vue路由組件路徑如何用變量形式動(dòng)態(tài)引入
這篇文章主要介紹了vue路由組件路徑如何用變量形式動(dòng)態(tài)引入問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-06-06
TypeError:res.forEach?is?not?a?function報(bào)錯(cuò)解決辦法
這篇文章主要給大家介紹了關(guān)于TypeError:res.forEach?is?not?a?function報(bào)錯(cuò)的解決辦法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2023-07-07
vue使用?vue-socket.io三種方式及踩坑實(shí)例解析
這篇文章主要為大家介紹了vue使用?vue-socket.io三種方式及踩坑實(shí)例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09
Vue3?封裝一個(gè)支持輸入和單/多選InputSelect組件-Antd詳解
Antd的Select組件默認(rèn)不支持作為輸入框使用或手動(dòng)添加選項(xiàng),為了實(shí)現(xiàn)這一功能,我們封裝了一個(gè)通用組件,支持單選和多選模式,并允許用戶在組件失焦時(shí)手動(dòng)輸入選項(xiàng),主要通過定義searchText存儲(chǔ)輸入數(shù)據(jù),感興趣的朋友跟隨小編一起看看吧2024-09-09
vue3快速實(shí)現(xiàn)主題切換功能的步驟詳解
本文介紹一種基于css變量的主題切換實(shí)現(xiàn)方式,這種是最簡單,最直接,最容易理解的方式,實(shí)現(xiàn)的原理就是定義不同的HTML根標(biāo)簽元素的樣式,通過data屬性來區(qū)分不同主題css變量樣式,感興趣的朋友可以參考下2024-06-06
vue中Npm run build 根據(jù)環(huán)境傳遞參數(shù)方法來打包不同域名
這篇文章主要介紹了vue項(xiàng)目中Npm run build 根據(jù)環(huán)境傳遞參數(shù)方法來打包不同域名,使用npm run build --xxx,根據(jù)傳遞參數(shù)xxx來判定不同的環(huán)境,給出不同的域名配置,具體內(nèi)容詳情大家參考下本文2018-03-03

