文件手动上传到oss
<a-upload
v-model="model.videoPath"
:show-upload-list="{ showRemoveIcon: true }"
:customRequest="handleUpload"
:multiple="false"
@preview="handlePreview"
@remove="handleRemove"
@change="handleChange"
:file-list="fileList"
:accept="'.mp4'"
>
<a-button>上传文件</a-button>
</a-upload>
handlePreview(e) {
window.open(this.model.videoPath, '_blank')
},
handleRemove(e) {
this.fileList = e.fileList
this.model.videoPath = ''
},
handleChange(e) {
const { file } = e
this.fileList = [file]
},
handleUpload({ file, onProgress, onSuccess, onError }) {
const filename = new Date().getTime() + randomUUID() + file.name
let _key = null
const that = this
getSignatureForOss({ biz: '存放路径' })
.then((res) => {
const data = JSON.parse(res.result)
const xhr = new XMLHttpRequest()
// 监听上传进度
xhr.upload.onprogress = (e) => {
if (e.lengthComputable) {
const percentComplete = Math.round((e.loaded * 100) / e.total)
onProgress({ percent: percentComplete }, file)
}
}
// 设置请求完成的处理函数
xhr.onload = () => {
if (xhr.status === 200) {
_key = `${data.dir}/${filename}`
this.$set(this.model, 'videoPath', `返回地址}`)
onSuccess({ code: 200 }, file) // 上传成功的回调
} else {
onError(xhr.statusText, file) // 上传失败的回调
}
}
// 错误处理
xhr.onerror = () => {
onError(xhr.statusText, file)
}
// 构建 FormData
const formData = new FormData()
formData.append('name', filename)
formData.append('policy', data.policy)
formData.append('OSSAccessKeyId', data.ossAccessKeyId)
formData.append('success_action_status', '200')
formData.append('signature', data.signature)
formData.append('key', `${data.dir}/${filename}`)
formData.append('file', file)
// 发送请求
xhr.open('POST', data.host, true)
xhr.send(formData)
})
.catch((error) => {
onError(error.message, file) // 处理 getSignatureForOss 可能的错误
})
},