feat: reader

This commit is contained in:
cuijiawang 2025-11-04 18:04:22 +08:00
parent c888dda2a2
commit eb413e91df
6 changed files with 774 additions and 173 deletions

View File

@ -3,16 +3,16 @@
"version": "1.0.0",
"private": true,
"scripts": {
"dev": "NODE_OPTIONS=--max-old-space-size=4096 vite",
"dev": "cross-env NODE_OPTIONS=--max-old-space-size=4096 vite",
"serve": "pnpm dev",
"build": "rimraf dist && NODE_OPTIONS=--max-old-space-size=8192 vite build",
"build": "rimraf dist && cross-env NODE_OPTIONS=--max-old-space-size=8192 vite build",
"build:staging": "rimraf dist && vite build --mode staging",
"report": "rimraf dist && vite build",
"preview": "vite preview",
"preview:build": "pnpm build && vite preview",
"typecheck": "tsc --noEmit && vue-tsc --noEmit --skipLibCheck",
"svgo": "svgo -f src/assets/svg -o src/assets/svg",
"cloc": "NODE_OPTIONS=--max-old-space-size=4096 cloc . --exclude-dir=node_modules --exclude-lang=YAML",
"cloc": "cross-env NODE_OPTIONS=--max-old-space-size=4096 cloc . --exclude-dir=node_modules --exclude-lang=YAML",
"clean:cache": "rimraf node_modules && rimraf .eslintcache && pnpm install",
"lint:eslint": "eslint --cache --max-warnings 0 \"{src,mock,build}/**/*.{vue,js,ts,tsx}\" --fix",
"lint:prettier": "prettier --write \"src/**/*.{js,ts,json,tsx,css,scss,vue,html,md}\"",
@ -82,6 +82,7 @@
"@vue/eslint-config-typescript": "^11.0.3",
"autoprefixer": "^10.4.14",
"cloc": "^2.11.0",
"cross-env": "^7.0.3",
"cssnano": "^6.0.1",
"eslint": "^8.43.0",
"eslint-plugin-prettier": "^4.2.1",

339
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

88
src/api/reader/index.ts Normal file
View File

@ -0,0 +1,88 @@
import { http } from "@/utils/http";
export interface TextFileQuery extends BasePageQuery {
fileName: string;
status: number;
}
export type TextFileDTO = {
fileId: number;
fileName: string;
originalFileName: string;
filePath: string;
fileSize: number;
description: string;
status: number;
uploadUserId: number;
uploadUserName: string;
createTime: Date;
updateTime: Date;
};
export type TextFileContentDTO = {
fileId: number;
fileName: string;
content: string;
fileSize: number;
};
/** 获取文本文件列表 */
export const getTextFileListApi = (params?: TextFileQuery) => {
return http.request<PageDTO<TextFileDTO>>("get", "/reader/file/list", {
params
});
};
/** 上传文本文件 */
export const uploadTextFileApi = (formData: FormData) => {
return http.request<ResponseData<number>>("post", "/reader/file/upload", {
data: formData,
headers: {
"Content-Type": "multipart/form-data"
}
});
};
/** 获取文件详情 */
export const getTextFileDetailApi = (fileId: number) => {
return http.request<ResponseData<TextFileDTO>>(
"get",
`/reader/file/detail/${fileId}`
);
};
/** 删除文件 */
export const deleteTextFileApi = (fileId: number) => {
return http.request<ResponseData<void>>("delete", `/reader/file/${fileId}`);
};
/** 批量删除文件 */
export const deleteBatchTextFileApi = (fileIds: Array<number>) => {
return http.request<ResponseData<void>>("delete", "/reader/file/batch", {
data: fileIds
});
};
/** 更新文件状态 */
export const updateTextFileStatusApi = (fileId: number, status: number) => {
return http.request<ResponseData<void>>(
"put",
`/reader/file/${fileId}/status/${status}`
);
};
/** 获取所有可用文件(用户端) */
export const getAllTextFilesApi = () => {
return http.request<ResponseData<Array<TextFileDTO>>>(
"get",
"/reader/public/files"
);
};
/** 读取文件内容 */
export const readTextFileApi = (fileId: number) => {
return http.request<ResponseData<TextFileContentDTO>>(
"get",
`/reader/public/read/${fileId}`
);
};

View File

@ -97,10 +97,25 @@ const onLogin = async (formEl: FormInstance | undefined) => {
// tokensessionStorage
setTokenFromBackend(data);
//
initRouter().then(() => {
router.push(getTopMenu(true).path);
message("登录成功", { type: "success" });
});
initRouter()
.then(() => {
const topMenu = getTopMenu(true);
if (topMenu && topMenu.path) {
router.push(topMenu.path);
message("登录成功", { type: "success" });
} else {
//
router.push("/welcome");
message("登录成功,但未分配菜单权限,请联系管理员", {
type: "warning"
});
}
})
.catch(error => {
console.error("路由初始化失败", error);
router.push("/welcome");
message("登录成功,但路由初始化失败", { type: "warning" });
});
if (isRememberMe.value) {
savePassword(ruleForm.password);
}
@ -143,8 +158,13 @@ async function fetchConfig() {
useUserStoreHook().SET_DICTIONARY(res.data.dictionary);
return true;
} catch (error) {
console.error("获取系统配置失败:", error);
return false;
console.warn("获取系统配置失败,使用默认配置:", error);
// 使
isCaptchaOn.value = false;
isPhoneRegisterOn.value = false;
clientId.value = "1";
useUserStoreHook().SET_DICTIONARY({});
return true; // true
}
}

View File

@ -0,0 +1,260 @@
<script setup lang="ts">
import { ref } from "vue";
import { useTextFileHook } from "./utils/hook";
import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { uploadTextFileApi } from "@/api/reader";
import { message } from "@/utils/message";
import Delete from "@iconify-icons/ep/delete";
import Search from "@iconify-icons/ep/search";
import Refresh from "@iconify-icons/ep/refresh";
import Upload from "@iconify-icons/ep/upload";
import { ElMessage } from "element-plus";
defineOptions({
name: "ReaderFile"
});
const tableRef = ref();
const searchFormRef = ref();
const uploadDialogVisible = ref(false);
const uploadFile = ref<File | null>(null);
const uploadDescription = ref("");
const uploading = ref(false);
const {
searchFormParams,
pageLoading,
columns,
dataList,
pagination,
defaultSort,
onSearch,
resetForm,
handleDelete,
handleBulkDelete,
handleStatusChange,
handleSelectionChange,
handleSizeChange,
handleCurrentChange
} = useTextFileHook();
function openUploadDialog() {
uploadDialogVisible.value = true;
uploadFile.value = null;
uploadDescription.value = "";
}
function handleFileChange(file: any) {
const uploadedFile = file.raw;
if (!uploadedFile.name.endsWith(".txt")) {
ElMessage.error("只支持上传txt文件");
return false;
}
if (uploadedFile.size > 100 * 1024 * 1024) {
ElMessage.error("文件大小不能超过100MB");
return false;
}
uploadFile.value = uploadedFile;
return false; //
}
async function handleUpload() {
if (!uploadFile.value) {
ElMessage.error("请选择要上传的文件");
return;
}
uploading.value = true;
try {
const formData = new FormData();
formData.append("file", uploadFile.value);
formData.append("description", uploadDescription.value);
await uploadTextFileApi(formData);
message("上传成功", { type: "success" });
uploadDialogVisible.value = false;
onSearch();
} catch (error) {
message("上传失败", { type: "error" });
} finally {
uploading.value = false;
}
}
// function formatFileSize(size: number) {
// if (size < 1024) {
// return `${size} B`;
// } else if (size < 1024 * 1024) {
// return `${(size / 1024).toFixed(2)} KB`;
// } else {
// return `${(size / (1024 * 1024)).toFixed(2)} MB`;
// }
// }
</script>
<template>
<div class="main">
<!-- 搜索栏 -->
<el-form
ref="searchFormRef"
:inline="true"
:model="searchFormParams"
class="search-form bg-bg_color w-[99/100] pl-8 pt-[12px]"
>
<el-form-item label="文件名:" prop="fileName">
<el-input
v-model="searchFormParams.fileName"
placeholder="请输入文件名或描述"
clearable
class="!w-[200px]"
/>
</el-form-item>
<el-form-item label="状态:" prop="status">
<el-select
v-model="searchFormParams.status"
placeholder="请选择状态"
clearable
class="!w-[180px]"
>
<el-option label="正常" :value="0" />
<el-option label="禁用" :value="1" />
</el-select>
</el-form-item>
<el-form-item>
<el-button
type="primary"
:icon="useRenderIcon(Search)"
:loading="pageLoading"
@click="onSearch"
>
搜索
</el-button>
<el-button
:icon="useRenderIcon(Refresh)"
@click="resetForm(searchFormRef, tableRef)"
>
重置
</el-button>
</el-form-item>
</el-form>
<PureTableBar title="文本文件列表" :columns="columns" @refresh="onSearch">
<template #buttons>
<el-button
type="primary"
:icon="useRenderIcon(Upload)"
@click="openUploadDialog"
>
上传文件
</el-button>
<el-button
type="danger"
:icon="useRenderIcon(Delete)"
@click="handleBulkDelete"
>
批量删除
</el-button>
</template>
<template v-slot="{ size, dynamicColumns }">
<pure-table
ref="tableRef"
adaptive
align-whole="center"
row-key="fileId"
showOverflowTooltip
:size="size"
:data="dataList"
:columns="dynamicColumns"
:pagination="pagination"
:paginationSmall="size === 'small' ? true : false"
:header-cell-style="{
background: 'var(--el-fill-color-light)',
color: 'var(--el-text-color-primary)'
}"
:loading="pageLoading"
:default-sort="defaultSort"
@selection-change="handleSelectionChange"
@page-size-change="handleSizeChange"
@page-current-change="handleCurrentChange"
>
<template #operation="{ row }">
<el-button
class="reset-margin"
link
type="primary"
:size="size"
@click="handleStatusChange(row)"
>
{{ row.status === 0 ? "禁用" : "启用" }}
</el-button>
<el-button
class="reset-margin"
link
type="danger"
:size="size"
@click="handleDelete(row)"
>
删除
</el-button>
</template>
</pure-table>
</template>
</PureTableBar>
<!-- 上传对话框 -->
<el-dialog
v-model="uploadDialogVisible"
title="上传文本文件"
width="500px"
:close-on-click-modal="false"
>
<el-form label-width="80px">
<el-form-item label="选择文件">
<el-upload
class="upload-demo"
:auto-upload="false"
:on-change="handleFileChange"
:limit="1"
accept=".txt"
:show-file-list="true"
>
<el-button type="primary">点击选择文件</el-button>
<template #tip>
<div class="el-upload__tip">只能上传txt文件且不超过100MB</div>
</template>
</el-upload>
</el-form-item>
<el-form-item label="文件描述">
<el-input
v-model="uploadDescription"
type="textarea"
:rows="3"
placeholder="请输入文件描述(可选)"
/>
</el-form-item>
</el-form>
<template #footer>
<span class="dialog-footer">
<el-button @click="uploadDialogVisible = false">取消</el-button>
<el-button type="primary" :loading="uploading" @click="handleUpload">
确定上传
</el-button>
</span>
</template>
</el-dialog>
</div>
</template>
<style scoped lang="scss">
.main {
width: 100%;
height: 100%;
padding: 10px;
}
</style>

View File

@ -0,0 +1,221 @@
import { message } from "@/utils/message";
import {
getTextFileListApi,
deleteTextFileApi,
deleteBatchTextFileApi,
updateTextFileStatusApi,
type TextFileQuery,
type TextFileDTO
} from "@/api/reader";
import { type PaginationProps } from "@pureadmin/table";
import { reactive, ref, onMounted } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
export function useTextFileHook() {
const searchFormParams = reactive<TextFileQuery>({
fileName: "",
status: undefined,
pageNum: 1,
pageSize: 10
});
const dataList = ref<Array<TextFileDTO>>([]);
const pageLoading = ref(true);
const multipleSelection = ref([]);
const columns: TableColumnList = [
{
type: "selection",
align: "left"
},
{
label: "序号",
type: "index",
index: (index: number) => {
return (
(searchFormParams.pageNum - 1) * searchFormParams.pageSize + index + 1
);
},
width: 70
},
{
label: "文件名",
prop: "originalFileName",
minWidth: 200
},
{
label: "文件大小",
prop: "fileSize",
minWidth: 100,
cellRenderer: ({ row }) => {
const size = row.fileSize;
if (size < 1024) {
return `${size} B`;
} else if (size < 1024 * 1024) {
return `${(size / 1024).toFixed(2)} KB`;
} else {
return `${(size / (1024 * 1024)).toFixed(2)} MB`;
}
}
},
{
label: "文件描述",
prop: "description",
minWidth: 200
},
{
label: "状态",
prop: "status",
minWidth: 100,
cellRenderer: ({ row }) => {
return (
<el-tag type={row.status === 0 ? "success" : "danger"}>
{row.status === 0 ? "正常" : "禁用"}
</el-tag>
);
}
},
{
label: "上传者",
prop: "uploadUserName",
minWidth: 120
},
{
label: "上传时间",
prop: "createTime",
minWidth: 160
},
{
label: "操作",
fixed: "right",
width: 180,
slot: "operation"
}
];
const pagination = reactive<PaginationProps>({
total: 0,
pageSize: 10,
currentPage: 1,
pageSizes: [10, 20, 50, 100],
background: true
});
const defaultSort = ref({
prop: "createTime",
order: "descending"
});
async function onSearch() {
pageLoading.value = true;
try {
const response = await getTextFileListApi(searchFormParams);
// 后端直接返回PageR对象
const pageData = response.data || response;
dataList.value = pageData.rows || [];
pagination.total = pageData.total || 0;
pagination.currentPage = searchFormParams.pageNum;
pagination.pageSize = searchFormParams.pageSize;
} catch (error) {
console.error("获取文件列表失败", error);
dataList.value = [];
pagination.total = 0;
} finally {
pageLoading.value = false;
}
}
const resetForm = (formEl, tableRef) => {
if (!formEl) return;
formEl.resetFields();
if (tableRef) {
tableRef.getTableRef().clearSort();
tableRef.getTableRef().clearFilter();
}
onSearch();
};
function handleDelete(row: TextFileDTO) {
ElMessageBox.confirm(`确认删除文件"${row.originalFileName}"吗?`, "提示", {
confirmButtonText: "确定",
cancelButtonText: "取消",
type: "warning"
})
.then(async () => {
await deleteTextFileApi(row.fileId);
message("删除成功", { type: "success" });
onSearch();
})
.catch(() => {});
}
function handleBulkDelete() {
if (multipleSelection.value.length === 0) {
ElMessage.warning("请至少选择一条数据");
return;
}
const fileIds = multipleSelection.value.map((item: any) => item.fileId);
const fileNames = multipleSelection.value
.map((item: any) => item.originalFileName)
.join("、");
ElMessageBox.confirm(`确认删除文件"${fileNames}"吗?`, "提示", {
confirmButtonText: "确定",
cancelButtonText: "取消",
type: "warning"
})
.then(async () => {
await deleteBatchTextFileApi(fileIds);
message("删除成功", { type: "success" });
onSearch();
})
.catch(() => {});
}
async function handleStatusChange(row: TextFileDTO) {
const newStatus = row.status === 0 ? 1 : 0;
try {
await updateTextFileStatusApi(row.fileId, newStatus);
message("状态更新成功", { type: "success" });
onSearch();
} catch (error) {
message("状态更新失败", { type: "error" });
}
}
const handleSelectionChange = val => {
multipleSelection.value = val;
};
const handleSizeChange = (val: number) => {
searchFormParams.pageSize = val;
onSearch();
};
const handleCurrentChange = (val: number) => {
searchFormParams.pageNum = val;
onSearch();
};
onMounted(() => {
onSearch();
});
return {
searchFormParams,
pageLoading,
columns,
dataList,
pagination,
defaultSort,
multipleSelection,
onSearch,
resetForm,
handleDelete,
handleBulkDelete,
handleStatusChange,
handleSelectionChange,
handleSizeChange,
handleCurrentChange
};
}