引入
npm install ali-oss
js
出现异常时,重新获取一下sts的token
import OSS from 'ali-oss'
import { csyApi } from '../api/csy'
let stsInfo = {
accessKeyId: null,
accessKeySecret: null,
securityToken: null,
bucketName: null,
dir: null,
requestId: null,
host: null
}
export function put (name, File) {
try {
return new Promise((resolve, reject) => {
if (!stsInfo.stsToken) {
return csyApi.stsToken().then(result => {
stsInfo = result.result
resolve(stsInfo)
})
} else {
resolve(stsInfo)
}
}).then(stsInfo => {
const client = new OSS({
region: 'oss-cn-shanghai',
accessKeyId: stsInfo.accessKeyId,
accessKeySecret: stsInfo.accessKeySecret,
bucket: stsInfo.bucketName,
stsToken: stsInfo.securityToken
})
return client.put(stsInfo.dir + name, File)
})
} catch (e) {
console.log(e)
}
}
组件 部分代码
**********************************
<a-upload
:disabled="initData.disabled"
name="avatar"
listType="picture-card"
class="avatar-uploader"
:showUploadList="false"
:customRequest="customRequest"
:beforeUpload="beforeUpload"
@change="handleChange"
>
<img class="nomal" v-if="imageUrl" :src="imageUrl" alt="avatar" />
<div v-else>
<a-icon :type="loading ? 'loading' : 'plus'" />
<div class="ant-upload-text">上传照片</div>
</div>
</a-upload>
**********************************
<script>
import { put } from '@/util/upload'
export default {
name: 'SUpload',
data () {
return {
loading: false,
imageUrl: ''
}
},
props: {
initData: {
type: Object,
required: true
},
formItemLayout: {
type: Object,
default: () => {
return { Col: {
md: 12
},
labelCol: {
md: 24
},
wrapperCol: {
md: 24
} }
}
}
},
methods: {
customRequest (action) {
const file = action.file
put(new Date().valueOf() + parseInt(Math.random() * 10000) + file.name.substring(0, 20), file).then(result => {
this.loading = false
this.imageUrl = result.url
}).catch(e => {
this.log('异常')
put(new Date().valueOf() + parseInt(Math.random() * 10000) + file.name.substring(0, 20), file).then(result => {
this.loading = false
this.imageUrl = result.url
})
})
},
handleChange (info) {
if (info.file.status === 'uploading') {
this.loading = true
}
},
beforeUpload (file) {
const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
if (!isJpgOrPng) {
this.$message.error('只允许上传图片')
}
const isLt10M = file.size / 1024 / 1024 < 10
if (!isLt10M) {
this.$message.error('图片最大10MB!')
}
if (isJpgOrPng && isLt10M) {
}
return isJpgOrPng && isLt10M
}
}
}
</script>
结束
有什么代码的错误 欢迎指正
---------------------
作者:SoOnPerson
来源:CSDN
原文:https://blog.csdn.net/qq_35793301/article/details/104987206
版权声明:本文为SoOnPerson原创文章,转载请附上博文链接!