Files
sgt_ca_app/src/components/Upload.vue

83 lines
2.3 KiB
Vue

<template>
<input v-model="props.fileId" hidden />
<a-upload
:accept="props.isPdf ? 'application/pdf' : 'image/*'"
action="/api2/upload/uploadfile"
v-model:fileList="fileList"
:beforeUpload="beforeUpload"
@change="handleChange"
:disabled="props.disabled"
>
<a-button block :disabled="props.disabled">
<UploadOutlined />
点击{{ props.fileId ? "替换" : "上传" }}
</a-button>
</a-upload>
</template>
<script>
import { UploadOutlined } from "@ant-design/icons-vue";
import { message } from "ant-design-vue";
import { ref } from "vue";
export default {
name: "Upload",
props: {
name: String,
fileId: Number,
fileUrl: String,
isPdf: Boolean,
disabled: Boolean
},
components: {
UploadOutlined
},
setup(props, context) {
var fileList = ref([]);
if (!props.fileId && props.fileUrl) {
fileList.value.push({
uid: "-1",
status: "done",
url: props.fileUrl,
name: props.fileName
});
}
const updateValue = value => {
context.emit("update:fileId", value); // 传递的方法
};
const beforeUpload = file => {
console.log(file);
const isValid =
props.isPdf === true
? file.type === "application/pdf"
: file.type === "image/jpeg" || file.type === "image/png";
if (!isValid) {
message.error("只能上传受支持格式的文件");
}
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isLt2M) {
message.error("文件大小超过2MB!");
}
return isValid && isLt2M;
};
const handleChange = info => {
console.log(info.file.status, info.file, info.fileList);
// if (info.file.status !== "uploading") {
// }
if (info.file.status === "done") {
message.success(`${info.file.name} 文件上传成功`);
updateValue(info.file.response.id);
if (info.fileList.length > 1) {
info.fileList.shift();
}
} else if (info.file.status === "error") {
message.error(`${info.file.name} 文件上传失败`);
info.fileList.pop();
}
if (info.file.status === "removed") {
updateValue(null);
}
};
return { props, fileList, beforeUpload, handleChange, updateValue };
}
};
</script>