這里是我參考的地址 https://blog.csdn.net/aiguo94/article/details/111832776
他里面有后台可以參考的,我這里只寫前端的
下載依賴 cnpm install ali-oss
html 部分,我這里是用的組件+element對話框+element上傳文件功能
先說一下element的上傳文件吧,我遇到的坑,上傳文件本身是有自動上傳的功能的,也就是一般會調用后台接口,但是oss是需要先在后台拿到一些參數,在上傳,所有
action="#" 被我置空,:auto-upload改為"false",auto-upload就是自動上傳的參數,具體的可以看一下element的文檔,auto-upload改為false就改成手動上傳了,所以在選擇文件時,想獲取到文件的信息,別的事件我用都不好使,只有個
:on-change事件好用,所以我就用的這個,在這個事件里獲取了文件的信息,名字,類型,大小等
這里就是調用接口,取后台給的參數

官網是這么說的:官網地址 https://help.aliyun.com/document_detail/111268.html?spm=a2c4g.11186623.6.1115.601728476iEKUl


我寫的思路表達完畢,現在上完整代碼,這里是組件內的,
<template>
<div>
<el-dialog title="上傳文件" :visible.sync="visible" width="30%" height="200px" center :close-on-click-modal="false" @close="close">
<el-form>
<el-form-item label="選擇文件:" label-width="120px">
<el-upload class="upload-demo inlineBlock"
ref="bigMap4UploadFile"
action="#"
:auto-upload="false"
:show-file-list="false"
:accept='parameter.accept'
:on-change="beforeAvatarUpload">
<el-button size="small" type="primary"><i class="el-icon-plus"></i> 選擇文件</el-button>
</el-upload>
<!-- <el-button id="uploadBtn" size="small" @click="upload()" style="background-color:rgba(86, 192, 13, 0.93);color: white;"> <i class="el-icon-upload"></i> 開始上傳</el-button> -->
<!-- <el-button id="stopBtn" size="small" v-show="showValue === 1" @click="stop()" style="background-color: indianred;color: white;margin-left:10px"> <i class="el-icon-close"></i> 取消大文件上傳</el-button> -->
</el-form-item>
<el-form-item label="文件支持格式:" label-width="120px">
<span class="el-upload__tip">{{parameter.accept}}</span>
</el-form-item>
</el-form>
<!-- <h2 id='status'>{{statusMsg}}</h2> -->
<!-- <img v-show="imgSrc" :src="imgSrc" alt="" class="img"> -->
<h3 v-show="img" class="relH3">{{img}} <i class="el-icon-delete absRight" @click="clearInfo"></i></h3>
<el-progress :percentage="progressValue" v-show="showValue==1"></el-progress>
<span slot="footer" class="dialog-footer">
<el-button @click="close">取 消</el-button>
<el-button type="primary" @click="confirm(true)" :disabled="buttonControl">確 定</el-button>
</span>
</el-dialog>
</div>
</template>
<script>
import $api from '@api'
// import { mapGetters } from 'vuex'
const OSS = require('ali-oss')
var credentials = null // STS憑證
var ossClient = null // oss客戶端實例
export default {
data () {
return {
statusMsg: '',
progressValue: 0,
showValue: 0,
imgSrc: null,
img: null,
visible: false, // 彈框是否顯示
fileInfo: null, // 選擇文件信息
backObj: {},
buttonControl: false
}
},
model: {
prop: 'videoUrl',
event: 'change'
},
/**
* parameter:Object 參數格式
* accept: 文件格式 eg: 'image/jpg,image/gif,image/png,image/jpeg,image/bmp,image/svg'
size: 限制最大文件 eg: 10 type:number
folder: 必填項 后台服務功能模塊 各個模塊不同,可以問后台此參數傳什么 eg: user //個人中心
# 會員中心 customer
# 工具服務 utility
# 設備租賃 rent
# 勞動力 uber
# 部品 bpsc
# 交易 trade
# 建築產品 jzsc
# 供需平台 snd
# 模型 model
modelFlag: 上傳模型傳1 ,默認不傳
*/
props: {
videoUrl: String,
parameter: Object
},
// computed: {
// ...mapGetters([
// 'bucketUrl'
// ])
// },
mounted () {
this.init()
},
methods: {
init () {
this.visible = true
},
// 確定
confirm () {
this.visible = false
if (this.backObj.name) {
this.$emit('change', this.backObj)
} else {
this.$emit('change', {})
}
},
// 關閉
close () {
this.visible = false
// console.log('關閉')
this.$emit('close', {})
},
// 選擇文件
beforeAvatarUpload (file) {
// 獲取文件名字,取到文件類型,就是文件后綴,為避免不同設備后綴大小寫不一致,統一改成大寫
var type
if (file.name || file.raw.type === '') {
var arr = file.name.split('.')
type = arr[arr.length - 1].toUpperCase()
}
// this.parameter.accept這個值是組件里的參數,是控制上傳文件格式的
if (this.parameter.accept && this.parameter.accept.toUpperCase().indexOf(type) <= 0) {
this.$message({ type: 'error', message: '格式不正確!', duration: 1000 })
return false
}
if (this.parameter.size) {
const isLt2M = file.size / 1024 / 1024 < this.parameter.size
if (!isLt2M) {
this.$message.error('大小不能超過 ' + this.parameter.size + 'MB!')
return false
}
}
this.buttonControl = true // 控制確定按鈕不能點擊,上傳成功才可點擊
this.fileInfo = file
this.img = file.name
this.upload()
},
// 清空
clearInfo () {
this.statusMsg = ''
this.$refs.bigMap4UploadFile.value = ''
this.progressValue = 0
this.showValue = 0
this.img = null
this.backObj = {}
},
// 上傳
upload () {
this.statusMsg = '上傳中'
$api.user.getStsToken({
modelFlag: this.parameter.modelFlag
}).then(({ data }) => {
// console.log(data)
if (data && data.head.retCode === '0000') {
credentials = data.body
const { accessKeyId, accessKeySecret, securityToken, bucketName } = credentials
if (!this.parameter.folder) return this.$message({ type: 'error', message: '服務功能模塊未上傳!', duration: 1000 })
ossClient = new OSS({
accessKeyId: accessKeyId,
accessKeySecret: accessKeySecret,
stsToken: securityToken,
bucket: bucketName, // utility
secure: true,
region: 'oss-cn-beijing', // todo
folder: this.parameter.folder
})
if (ossClient) {
var { raw } = this.fileInfo
var fileList = [raw]
fileList.forEach(file => {
// 如果文件大學小於分片大小,使用普通上傳,否則使用分片上傳
// if (file.size < partSize) {
// this.showValue = 0
// this.commonUpload(file)
// } else {
this.showValue = 1
this.multipartUpload(file)
// }
})
} else {
this.$message({ type: 'error', message: '服務端響應異常!', duration: 1000 })
this.statusMsg = 'initOSSClient異常空,請刷新重試或聯系管理員'
}
} else {
this.$message({ type: 'error', message: '服務端響應異常!', duration: 1000 })
this.statusMsg = 'sts臨時憑證獲取失敗,請刷新重試或聯系管理員'
}
}).catch(err => {
this.$message({ type: 'error', message: '服務端響應異常!', duration: 1000 })
this.statusMsg = err + 'initOSSClient異常,請刷新重試或聯系管理員'
})
},
// 添加文件夾名字
getDateFolder () {
const t = new Date()
let timeStr = ''
timeStr = timeStr + t.getFullYear() // 年
timeStr = timeStr + (t.getMonth() + 1)// 月,因為從0開始,所以需要加1
timeStr = timeStr + t.getDate() // 日
return timeStr
},
// 普通上傳
commonUpload (file) {
// var fileName = file.name
var newFileName = new Date().getTime() + Math.random().toString(36).substr(2) + file.name.substr(file.name.lastIndexOf('.'))
return ossClient.put(this.parameter.folder + '/' + newFileName, file).then(result => {
// console.log(`Common upload ${file.name} succeeded, result === `, result)
this.imgSrc = result.url // 此頁面可用來展示圖片
this.backObj = result
this.backObj.size = file.size
this.backObj.oldName = file.name
this.buttonControl = false
}).catch(err => {
this.statusMsg = '上傳失敗'
this.buttonControl = true
console.log(`Common upload ${file.name} failed === `, err)
})
},
// 分片上傳
multipartUpload (file) {
// oss上傳到服務器上的名字 我這是后台服務名字+時間戳+6位隨機數
var newFileName = new Date().getTime() + Math.random().toString(36).substr(2) + file.name.substr(file.name.lastIndexOf('.'))
return ossClient.multipartUpload(this.parameter.folder + '/' + newFileName, file, {
progress: this.onMultipartUploadProgress
}).then(result => {
this.statusMsg = '上傳成功'
this.backObj = result
this.backObj.size = file.size
this.backObj.oldName = file.name
this.buttonControl = false
// console.log('上傳成功')
}).catch(err => {
console.log('上傳失敗')
this.statusMsg = '上傳失敗'
console.log(`Multipart upload ${file.name} failed === `, err)
this.progressValue = 0
this.showValue = 0
this.buttonControl = true
})
},
// 分片上傳進度改變回調
onMultipartUploadProgress (progress, checkpoint) {
// console.log(`${checkpoint.file.name} 上傳進度 ${progress}`)
// checkpoints[checkpoint.uploadId] = checkpoint
this.progressValue = Math.round(progress * 100)
},
// 停止上傳
stop () {
this.statusMsg = '停止上傳'
if (ossClient) {
ossClient.cancel()
} else {
this.statusMsg = '停止失敗'
}
}
}
}
</script>
<style scoped lang="scss">
.avatar {
width: 178px;
height: 178px;
display: block;
}
.img{
width: 178px;
height: 178px;
}
.relH3{
padding: 0 27px;
position: relative;
}
.absRight{
position: absolute;
right:10px;
}
</style>
這里是引用組件所寫的,有點散,我就上圖了



