web端oss直传方案之vue+elementUI+OSS实践篇(附各种踩坑)
<template>
<el-upload
:action="uploadUrl"
:before-upload="beforeUpload"
:on-success="handleSuccess"
:on-error="handleError"
:data="policyData">
<el-button size="small" type="primary">点击上传</el-button>
</el-upload>
</template>
<script>
import { getOssSignature } from '@/api/oss'
export default {
data() {
return {
uploadUrl: '',
policyData: {
'key': '',
'policy': '',
'OSSAccessKeyId': '',
'signature': '',
}
}
},
methods: {
beforeUpload(file) {
// 获取OSS签名
getOssSignature().then(response => {
const data = response.data
this.policyData.key = data.dir + '/${filename}'
this.policyData.policy = data.policy
this.policyData.OSSAccessKeyId = data.accessid
this.policyData.signature = data.signature
this.uploadUrl = data.host
})
return false // 阻止默认上传行为
},
handleSuccess(response, file, fileList) {
// 处理上传成功
console.log('File uploaded successfully:', file)
},
handleError(err, file, fileList) {
// 处理上传失败
console.error('Error during upload:', err)
}
}
}
</script>
这个代码实例展示了如何在Vue.js应用中使用Element UI的<el-upload>
组件结合后端API来实现OSS直传。在上传文件之前,它会向后端请求签名信息,并在前端设置上传参数。这种方式避免了将文件数据传输到服务器再由服务器传给OSS的中间步骤,从而提升了用户体验和减少了服务器压力。
评论已关闭