1. 首先安装oss
npm install ali-oss --save
2.
// template部分 <Upload ref="upload" type="drag" :default-file-list="file" action="" :before-upload="handleBeforeUpload" :on-preview="handlePreview" :on-remove="handleRemove" :accept="accept" with-credentials> <div style="padding: 20px 0"> <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon> <p>点击或拖拽上传文件</p> </div> </Upload> <Progress :percent="uploadPercent" v-if="isPercent"/>
3. script部分
<script>
export deault {
data () {
return {
file: [],
accept: 'video/*',
ossConfig: {},
ossInfo: {},
isPercent: false,
uploadPercent: 0,
format:[],
maxSize: 1 * 1024 * 1024
}
},
methods: {
// 获取上传凭证
async getUploadToken () {
// 通过后端接口获取上传基本信息
const res = await getUploadInfo(params)
this.ossConfig = {
region: res.data.region_id,
accessKeyId: res.data.AccessKeyId,
accessKeySecret: res.data.AccessKeySecret,
stsToken: res.data.SecurityToken,
bucket: res.data.bucket,
secure: true
}
this.ossInfo = {
Expiration: res.data.Expiration,
dir: res.data.dir,
domain: res.data.domain,
filename: res.data.filename
}
},
// 定义上传方法。
async multipartUpload (filename, file) {
try {
const result = await
this.client.multipartUpload(`${this.ossInfo.dir}${this.ossInfo.filename}.${this.fileSuffix}`, file, {
headers: {
'Content-Disposition': 'inline',
'Content-Type': this.fileType
},
progress: (p, checkpoint) => {
this.isPercent = true
this.uploadPercent = Number((p * 100).toFixed(2))
// checkpoint参数用于记录上传进度,断点续传上传时将记录的checkpoint参数传入即可。浏览器重启后无法直接继续上传,您需要手动触发上传操作。
this.tempPoint = checkpoint
},
parallel: 10,
// 设置分片大小 默认是1M,这里设置5M
partSize: 1024 * 1024 * 5,
mime: this.fileType
})
if (result.res.statusCode !== 200) {
this.$Message.error('文件上传失败')
return false
}
this.file = [
{
name: this.fileName,
url: this.ossInfo.domain + result.name
}
]
this.$Message.success(`文件上传成功`)
this.isPercent = false
} catch (e) {
this.$Message.error('文件上传失败')
this.isPercent = false
}
},
// 上传前处理
handleBeforeUpload (file, fileList) {
this.fileSuffix = file.name.split('.').pop()
this.fileName = file.name
this.fileType = file.type
if (!this.format.includes(this.fileSuffix)) {
this.$Message.error(`上传文件仅支持${this.format.toString()}格式`)
return false
}
if (file.size > this.maxSize) {
this.$Message.error(`当前上传文件最大不能超过100M`)
return false
}
this.client = new OSS(this.ossConfig)
this.multipartUpload(file.name, file)
return false
},
}
}
</script>
posted on
浙公网安备 33010602011771号