You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
WeChat/src/views/modules/oss/oss-uploader.vue

73 lines
2.6 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<template>
<!-- 点击外部div触发文件选择操作 -->
<div @click="selectFile">
<!-- inputonFileChange -->
<input type="file" ref="fileInput" v-show="false" @change="onFileChange" />
<!-- 显示上传中的状态或默认的上传文件文本 -->
<div>{{uploading ? infoText : '上传文件'}}</div>
</div>
</template>
<script>
export default {
name: "oss-uploader", // 组件名称为 "oss-uploader"
data() {
return {
uploading: false, // 上传状态默认为false
infoText: "上传中...", // 上传中文本,上传中时显示此文本
cosConfig: [] // 存储云存储配置
}
},
mounted() {
// 组件挂载后请求获取云存储的配置
this.$http({
url: this.$http.adornUrl('/sys/oss/config'), // 获取配置的API接口
method: 'get', // 使用GET请求
params: this.$http.adornParams() // 请求参数
}).then(({ data }) => {
// 请求成功后处理返回数据
if (data && data.code === 200 && data.config.type) {
this.cosConfig = data.config // 设置云存储配置
} else {
// 如果配置不存在,弹出错误提示
this.$message.error('请先配置云存储相关信息!')
}
})
},
methods: {
// 选择文件的事件处理函数
selectFile() {
if (!this.uploading) {
// 如果当前不是上传中状态则模拟点击隐藏的input元素打开文件选择框
this.$refs.fileInput.click();
}
},
// 文件选择后触发的事件处理函数
onFileChange() {
let file = this.$refs.fileInput.files[0]; // 获取文件对象
this.uploading = true; // 设置上传状态为true表示正在上传
let formData = new FormData();
formData.append("file", file); // 将文件添加到formData对象中
// 发起POST请求上传文件
this.$http({
url: this.$http.adornUrl('/sys/oss/upload'), // 上传文件的API接口
method: 'post', // 使用POST请求
data: formData // 上传的文件数据
}).then(({ data }) => {
// 请求成功后处理返回的数据
console.log(data); // 输出返回的数据,便于调试
if (data && data.code === 200) {
// 上传成功,触发父组件的'uploaded'事件传递上传后的文件url
this.$emit('uploaded', data.url)
} else {
// 上传失败,弹出错误提示,显示错误信息
this.$message.error("文件上传失败:" + data.msg)
}
this.uploading = false; // 上传完成设置上传状态为false
})
}
}
}
</script>