使用 element-ui 的上传组件 upload 完成自定义上传到天翼云 oss 云服务器
本文分享自天翼云开发者社区 @《使用element-ui 的上传组件upload完成自定义上传到天翼云oss云服务器》,作者: 我是小朋友
首先配置天翼云,如下操作
1、要求
在使用 OOS 之前,首先需要在 www.ctyun.cn 注册一个账号(Account)。 创建 AccessKeyId 和 AccessSecretKey。AccessKeyId 和 AccessSecretKey 是您访 问 OOS 的密钥,OOS 会通过它来验证您的资源请求,请妥善保管
2 、使用方式
<!—引入本地资源-->
<script src="./oos-sdk-x.x.x.min.js"></script>
使用 new OOS 创建 oos 对象 OOS JS-SDK 目前只支持异步请求方式,通过 callback 方式处理,对于 err 处理,非 err 显示处理结果。下图示例初始化到返回结果流程:
var client = new OOS.S3({...});
var params;
client.listObjects(params, function (err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
3、 CORS 配置
从浏览器中直接访问 OOS 需要开通 Bucket 的 CORS:
• 将 来源(*)设置成: *
• 将允许的方法(*)设置成: PUT, GET, POST, DELETE, HEAD
• 将允许的 Headers 设置成: *
• 将暴露的 Headers:设置成: ETag 注意:请将该条 CORS 规则设置成所有 CORS 规则的第一条
由于浏览器的同源策略,在浏览器里调用 JS-SDK 时, 部分功能无法实现,包括 Service 的 操作,Bucket 的新建,AccessKey 以及 SecretKey 的操作
4、options 配置项
OOS options 介绍
封装上传组件如下:
<template>
<div :class="{exceed: isExceed}">
<el-upload ref="upload" action="#" :http-request="httpRequest" :before-upload="beforeUpload"
list-type="picture-card" :on-preview="handlePictureCardPreview" :file-list="fileList" :on-remove="handleRemove"
v-bind="$attrs" :on-exceed="handleOnExceed" :on-success="handleOnSuccess" :on-change="onChangeFile">
<i class="el-icon-plus"></i>
</el-upload>
<i v-if="bottomTip">{{bottomTip}}</i>
<el-dialog :visible.sync="dialogVisible" append-to-body>
<img width="100%" :src="dialogImageUrl">
</el-dialog>
<image-viewer :z-index="3000" v-if="showViewer" :on-close="closeViewer" :url-list="previewSrcList" />
</div>
</template>
<script>
import imageViewer from 'element-ui/packages/image/src/image-viewer'
var Bucket = '********'
var accessKeyId = '********'
var secretAccessKey = '********'
var endPoint = 'oos-cn.ctyunapi.cn'
export default {
name: 'd2-upload',
components: { imageViewer },
props: {
value: {
type: Array,
default () {
return []
}
},
bottomTip: {
type: String
},
removeAfterUpload: {
type: Boolean,
default () {
return false
}
}
},
data () {
return {
fileList: [],
uploadList: [], // 自定义的数组,用于处理 fileList,fileList 是只读的
dialogImageUrl: '',
dialogVisible: false,
isInternal: false,
isExceed: false,
showViewer: false,
previewSrcList: [],
clent: null
}
},
watch: {
value: {
handler (val) {
if (!this.isInternal) {
if (!this.uploadList.length) {
this.fileList = val.map(item => {
return {
url: item
}
})
}
this.setIsExceed()
} else {
this.isInternal = false
}
},
immediate: true
}
},
methods: {
// 选择上传文件,上传成功后都会出发
onChangeFile (file, fileList) {
this.fileList = fileList
let index = this.fileList.findIndex(item => {
return file.raw.response === item.raw.response
})
if (file.raw.response) {
this.uploadList.splice(index, 0, file.raw.response)
this.emitData(this.uploadList)
}
},
async httpRequest (file) {
await this.handleUpload(file.file)
},
handleUpload (file) {
this.isInternal = true
return new Promise((resolve, reject) => {
let that = this
var params = {
Body: file,
Bucket: Bucket,
Key: file.name
}
that.client.putObject(params, function (err, data) {
if (err) {
console.log(err, err.stack) // an error occurred
resolve(false)
that.$message.error('上传失败')
} else {
file.response = 'https://' + endPoint + '/' + params.Bucket + '/' + params.Key
that.$message.success('上传成功')
that.isInternal = false
resolve(true)
}
})
})
},
initOss () {
this.client = new OOS.S3({
accessKeyId: accessKeyId,
secretAccessKey: secretAccessKey,
endpoint: endPoint,
signatureVersion: 'v4', // 可选 v2 或 v4
apiVersion: '2006-03-01',
s3ForcePathStyle: true
})
},
beforeUpload (file) {
},
handleOnExceed (file, fileList) {
this.$message.warning('数量超出限制')
},
handleRemove (file, fileList) {
let index = this.fileList.findIndex(item => {
if (file.raw) {
return file.raw.response === item.raw.response
} else {
return file.url === item.url
}
})
this.uploadList.splice(index, 1)
this.isInternal = true
this.fileList = fileList
this.emitData(this.uploadList)
this.isExceed = false
},
handlePictureCardPreview (file) {
this.previewSrcList = [file.raw.response]
this.showViewer = true
},
handleOnSuccess (response, file, fileList) {
this.fileList = fileList
this.isInternal = true
this.setIsExceed()
if (this.removeAfterUpload) {
this.$refs.upload.clearFiles()
this.uploadList = []
}
},
emitData (list) {
this.$emit('input', list)
},
closeViewer () {
this.showViewer = false
},
setIsExceed () {
if (this.$attrs.limit && this.fileList.length >= this.$attrs.limit) {
this.isExceed = true
} else {
this.isExceed = false
}
}
},
mounted () {
this.initOss()
}
}
</script>
<style scoped>
.exceed >>> .el-upload {
display: none;
}
</style>
组件引用:
<d2-upload v-model="form.uploaderUrlArray" :limit="5" accept=".png,.jpg,.jpeg" multiple />
————————————————
版权声明:本文为 CSDN 博主「包淼淼」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_32849999/article/details/110000814
评论