Files
fe-manage/src/components/project/ImageUpload.vue
2024-09-26 16:40:00 +08:00

125 lines
3.3 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<template>
<div>
<input type="file" @change="handleFileUpload" />
<img :src="avatarUrl" alt="Avatar" v-if="avatarUrl" />
</div>
</template>
<script>
export default {
data() {
return {
avatarUrl: '' // 存储头像的 URLBase64 编码或服务器 URL
};
},
methods: {
handleFileUpload(event) {
const file = event.target.files[0]; // 获取用户选择的文件
if (!file) return;
// 创建一个 FileReader 实例
const reader = new FileReader();
// 读取文件内容,并在读取完成后设置 img 的 src
reader.onload = (e) => {
this.avatarUrl = e.target.result; // e.target.result 是 Base64 编码的字符串
};
// 读取文件内容(作为 DataURL
reader.readAsDataURL(file);
// 如果你需要上传文件到服务器,可以在这里添加代码
// 例如,使用 Axios 发送 POST 请求到服务器
}
}
};
</script>
<!-- <template>
<a-upload
:file-list="files"
:action="FILE_UPLOAD_URL"
:show-upload-list="showUploadList"
:multiple="multiple"
:before-upload="beforeUpload"
:headers="headers"
@change="handleChange"
ref="imageRef"
>
<template v-for="(_, key, index) in $slots" :key="index" v-slot:[key]>
<slot :name="key"></slot>
</template>
</a-upload>
</template>
<script setup>
import {defineProps, defineEmits, defineExpose, ref, watch} from "vue";
import {message} from "ant-design-vue";
import {FILE_UPLOAD_URL} from "@/api/config";
import {getCookieForName} from "@/api/method";
const props = defineProps({
value: {
type: Array,
default: () => []
},
multiple: {
type: Boolean,
default: fals
},
showUploadList: {
type: Boolean,
default: false
},
fileType: {
type: Array,
default: () => []
}
})
const emit = defineEmits({})
const files = ref([])
const imageRef = ref()
const headers = { token: getCookieForName("token") };
watch(props, () => {
props.value.length !== files.value.length && (files.value = props.value)
})
function handleChange({file, fileList}) {
file.response && file.response.code === 200 && (file.url = file.response.data)
files.value = fileList
emit('update:value', fileList)
}
function beforeUpload(file) {
if (!props.fileType.includes(file.name.split(".").slice(-1).join(''))) {
message.error(
"不支持该格式"
);
return false;
}
}
function remove(i) {
files.value.splice(i, 1)
emit('update:value', files.value)
}
function reUpload(i) {
if (files.value[i].status === 'ready' || files.value[i].status === 'uploading') {
imageRef.value.abort(files.value[i].raw)
files.value[i].status = 'abort';
} else if (files.value[i].status === 'fail' || files.value[i].status === 'abort') {
imageRef.value.handleStart(files.value[i].raw)
imageRef.value.submit()
}
}
function abort(i) {
imageRef.value.abort(files.value[i].raw)
}
defineExpose({reUpload, remove, abort})
</script> -->