ソースを参照

1、完成文件管理页面对接 2、优化其他

zuohuaijun 3 年 前
コミット
45e12dc90b

+ 3 - 3
Admin.NET/Admin.NET.Core/Admin.NET.Core.csproj

@@ -28,8 +28,8 @@
     <PackageReference Include="Furion.Extras.ObjectMapper.Mapster" Version="4.6.5" />
     <PackageReference Include="Furion.Pure" Version="4.6.5" />
     <PackageReference Include="Lazy.Captcha.Core" Version="1.1.6" />
-    <PackageReference Include="Magicodes.IE.Excel" Version="2.6.7" />
-    <PackageReference Include="Magicodes.IE.Pdf" Version="2.6.7" />
+    <PackageReference Include="Magicodes.IE.Excel" Version="2.6.8" />
+    <PackageReference Include="Magicodes.IE.Pdf" Version="2.6.8" />
     <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="6.0.10" />
     <PackageReference Include="NEST" Version="7.17.4" />
     <PackageReference Include="NETCore.MailKit" Version="2.1.0" />
@@ -41,7 +41,7 @@
     <PackageReference Include="System.Linq.Dynamic.Core" Version="1.2.20" />
     <PackageReference Include="UAParser" Version="3.1.47" />
     <PackageReference Include="Yitter.IdGenerator" Version="1.0.14" />
-    <PackageReference Include="Masuit.Tools.Core" Version="2.5.5.1" />
+    <PackageReference Include="Masuit.Tools.Core" Version="2.5.6" />
   </ItemGroup>
 
   <ItemGroup>

+ 18 - 4
Admin.NET/Admin.NET.Core/Admin.NET.Core.xml

@@ -2974,14 +2974,14 @@
         </member>
         <member name="M:Admin.NET.Core.ObjectExtension.ParseToDouble(System.Object)">
             <summary>
-            将object转换为double,若失败则返回0  
+            将object转换为double,若失败则返回0
             </summary>
             <param name="obj"></param>
             <returns></returns>
         </member>
         <member name="M:Admin.NET.Core.ObjectExtension.ParseToDouble(System.Object,System.Double)">
             <summary>
-            将object转换为double,若失败则返回指定值 
+            将object转换为double,若失败则返回指定值
             </summary>
             <param name="str"></param>
             <param name="defaultValue"></param>
@@ -2989,14 +2989,14 @@
         </member>
         <member name="M:Admin.NET.Core.ObjectExtension.ParseToDateTime(System.String)">
             <summary>
-            将string转换为DateTime,若失败则返回日期最小值 
+            将string转换为DateTime,若失败则返回日期最小值
             </summary>
             <param name="str"></param>
             <returns></returns>
         </member>
         <member name="M:Admin.NET.Core.ObjectExtension.ParseToDateTime(System.String,System.Nullable{System.DateTime})">
             <summary>
-            将string转换为DateTime,若失败则返回默认值  
+            将string转换为DateTime,若失败则返回默认值
             </summary>
             <param name="str"></param>
             <param name="defaultValue"></param>
@@ -7756,6 +7756,20 @@
             </summary>
             <returns></returns>
         </member>
+        <member name="M:Admin.NET.Core.DateTimeUtil.GetWeekByDate(System.DateTime)">
+            <summary>
+            获取星期几
+            </summary>
+            <param name="dt"></param>
+            <returns></returns>
+        </member>
+        <member name="M:Admin.NET.Core.DateTimeUtil.GetWeekNumInMonth(System.DateTime)">
+            <summary>
+            获取这个月的第几周
+            </summary>
+            <param name="daytime"></param>
+            <returns></returns>
+        </member>
         <member name="T:Admin.NET.Core.LongJsonConverter">
             <summary>
             序列化时long转string(防止js精度溢出)

+ 11 - 11
Admin.NET/Admin.NET.Core/Service/File/SysFileService.cs

@@ -41,7 +41,7 @@ public class SysFileService : IDynamicApiController, ITransient
             .WhereIF(!string.IsNullOrWhiteSpace(input.FileName), u => u.FileName.Contains(input.FileName.Trim()))
             .WhereIF(!string.IsNullOrWhiteSpace(input.StartTime.ToString()) && !string.IsNullOrWhiteSpace(input.EndTime.ToString()),
                         u => u.CreateTime >= input.StartTime && u.CreateTime <= input.EndTime)
-            .OrderBy(u => u.CreateTime, SqlSugar.OrderByType.Desc)
+            .OrderBy(u => u.CreateTime, OrderByType.Desc)
             .ToPagedListAsync(input.Page, input.PageSize);
     }
 
@@ -104,13 +104,13 @@ public class SysFileService : IDynamicApiController, ITransient
         {
             var filePath = string.Concat(file.FilePath, "/", input.Id.ToString() + file.Suffix);
             var stream = await (await _OSSService.PresignedGetObjectAsync(file.BucketName.ToString(), filePath, 5)).GetAsStreamAsync();
-            return new FileStreamResult(stream.Stream, "application/octet-stream") { FileDownloadName = fileName };
+            return new FileStreamResult(stream.Stream, "application/octet-stream") { FileDownloadName = fileName + file.Suffix };
         }
         else
         {
             var filePath = Path.Combine(file.FilePath, input.Id.ToString() + file.Suffix);
             var path = Path.Combine(App.WebHostEnvironment.WebRootPath, filePath);
-            return new FileStreamResult(new FileStream(path, FileMode.Open), "application/octet-stream") { FileDownloadName = fileName };
+            return new FileStreamResult(new FileStream(path, FileMode.Open), "application/octet-stream") { FileDownloadName = fileName + file.Suffix };
         }
     }
 
@@ -188,7 +188,7 @@ public class SysFileService : IDynamicApiController, ITransient
             FileName = Path.GetFileNameWithoutExtension(file.FileName),
             Suffix = suffix,
             SizeKb = sizeKb.ToString(),
-            FilePath = path
+            FilePath = path,            
         };
 
         var finalName = newFile.Id + suffix; // 文件最终名称
@@ -206,24 +206,24 @@ public class SysFileService : IDynamicApiController, ITransient
                     break;
 
                 case OSSProvider.Minio:
-                    //获取Minio文件的下载或者预览地址
+                    // 获取Minio文件的下载或者预览地址
                     newFile.Url = await GetMinioPreviewFileUrl(newFile.BucketName, filePath); ;
                     break;
             }
         }
         else
         {
-            newFile.Provider = "";//本地存储 Provider 显示为空
+            newFile.Provider = ""; // 本地存储 Provider 显示为空
             var filePath = Path.Combine(App.WebHostEnvironment.WebRootPath, path);
             if (!Directory.Exists(filePath))
                 Directory.CreateDirectory(filePath);
 
             var realFile = Path.Combine(filePath, finalName);
-            await using var stream = File.Create(realFile);
+            using var stream = File.Create(realFile);
+
             await file.CopyToAsync(stream);
             var detector = stream.DetectFiletype();
-            var realExt = detector.Extension;//真实扩展名
-
+            var realExt = detector.Extension; // 真实扩展名
             // 二次校验扩展名
             if (!string.Equals(realExt, suffix.Replace(".", ""), StringComparison.OrdinalIgnoreCase))
             {
@@ -233,7 +233,7 @@ public class SysFileService : IDynamicApiController, ITransient
                 throw Oops.Oh(ErrorCodeEnum.D8001);
             }
 
-            //生成外链
+            // 生成外链
             newFile.Url = _commonService.GetFileUrl(newFile);
         }
         await _sysFileRep.AsInsertable(newFile).ExecuteCommandAsync();
@@ -246,7 +246,7 @@ public class SysFileService : IDynamicApiController, ITransient
     /// <param name="bucketName">桶名</param>
     /// <param name="fileName">文件名</param>
     /// <returns></returns>
-    private async Task<string> GetMinioPreviewFileUrl(String bucketName, String fileName)
+    private async Task<string> GetMinioPreviewFileUrl(string bucketName, string fileName)
     {
         return await _OSSService.PresignedGetObjectAsync(bucketName, fileName, 7);
     }

+ 0 - 1
Admin.NET/Admin.NET.Core/Service/User/SysUserService.cs

@@ -67,7 +67,6 @@ public class SysUserService : IDynamicApiController, ITransient
         var user = input.Adapt<SysUser>();
         user.Password = MD5Encryption.Encrypt(CommonConst.SysPassword);
         input.Id = (await _sysUserRep.AsInsertable(user).ExecuteReturnEntityAsync()).Id;
-        user.Status = StatusEnum.Enable;
 
         await UpdateUserRole(input);
     }

+ 2 - 2
Admin.NET/Admin.NET.Core/SqlSugar/SqlSugarRepository.cs

@@ -8,9 +8,9 @@ public class SqlSugarRepository<T> : SimpleClient<T> where T : class, new()
 {
     protected ITenant iTenant = null; // 多租户事务
 
-    public SqlSugarRepository(ISqlSugarClient context = null) : base(context) // 默认值等于null不能少
+    public SqlSugarRepository(ISqlSugarClient context = null) : base(context)
     {
         iTenant = App.GetService<ISqlSugarClient>().AsTenant();
-        base.Context = iTenant.GetConnectionWithAttr<T>();
+        Context = iTenant.GetConnectionWithAttr<T>();
     }
 }

+ 32 - 0
Admin.NET/Admin.NET.Core/Util/DateTimeUtil.cs

@@ -133,4 +133,36 @@ public class DateTimeUtil
             Convert.ToDateTime(time.AddDays(1).ToString("D").ToString()).AddSeconds(-1)
         };
     }
+
+    /// <summary>
+    /// 获取星期几
+    /// </summary>
+    /// <param name="dt"></param>
+    /// <returns></returns>
+    public static string GetWeekByDate(DateTime dt)
+    {
+        var day = new[] { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
+        return day[Convert.ToInt32(dt.DayOfWeek.ToString("d"))];
+    }
+
+    /// <summary>
+    /// 获取这个月的第几周
+    /// </summary>
+    /// <param name="daytime"></param>
+    /// <returns></returns>
+    public static int GetWeekNumInMonth(DateTime daytime)
+    {
+        int dayInMonth = daytime.Day;
+        // 本月第一天
+        DateTime firstDay = daytime.AddDays(1 - daytime.Day);
+        // 本月第一天是周几
+        int weekday = (int)firstDay.DayOfWeek == 0 ? 7 : (int)firstDay.DayOfWeek;
+        // 本月第一周有几天
+        int firstWeekEndDay = 7 - (weekday - 1);
+        // 当前日期和第一周之差
+        int diffday = dayInMonth - firstWeekEndDay;
+        diffday = diffday > 0 ? diffday : 1;
+        // 当前是第几周,若整除7就减一天
+        return ((diffday % 7) == 0 ? (diffday / 7 - 1) : (diffday / 7)) + 1 + (dayInMonth > firstWeekEndDay ? 1 : 0);
+    }
 }

+ 1 - 1
Admin.NET/Admin.NET.Core/Util/LongJsonConverter.cs

@@ -15,6 +15,6 @@ public class LongJsonConverter : JsonConverter<long>
     public override long ReadJson(JsonReader reader, Type objectType, long existingValue, bool hasExistingValue, JsonSerializer serializer)
     {
         JToken jt = JValue.ReadFrom(reader);
-        return string.IsNullOrWhiteSpace(jt.Value<string>())?0: jt.Value<long>();
+        return string.IsNullOrWhiteSpace(jt.Value<string>()) ? 0 : jt.Value<long>();
     }
 }

+ 2 - 0
Admin.NET/Admin.NET.Web.Core/Startup.cs

@@ -25,6 +25,8 @@ public class Startup : AppStartup
     {
         // 配置选项
         services.AddProjectOptions();
+        // 控制台格式化
+        services.AddConsoleFormatter();
         // 缓存注册
         services.AddCache();
         // SqlSugar

+ 18 - 27
vue-next-admin/src/utils/axios-utils.ts

@@ -11,19 +11,8 @@ import { BaseAPI, BASE_PATH } from '/@/api-services/base';
 import { ElMessage } from 'element-plus';
 import { Local, Session } from '/@/utils/storage';
 
-// 如果是 Angular 项目,则取消下面注释即可
-// import { environment } from './environments/environment';
-
-/**
- * 接口服务器配置
- */
+// 接口服务器配置
 export const serveConfig = new Configuration({
-	// 如果是 Angular 项目,则取消下面注释,并删除 process.env.NODE_ENV !== "production"
-	// basePath: !environment.production
-	// basePath:
-	// 	process.env.NODE_ENV !== 'production'
-	// 		? 'https://localhost:44326' // 开发环境服务器接口地址
-	// 		: 'https://*:5005', // 生产环境服务器接口地址
 	basePath: import.meta.env.VITE_API_URL,
 });
 
@@ -43,9 +32,7 @@ const clearAccessTokens = () => {
 	window.location.reload();
 };
 
-/**
- * axios 默认实例
- */
+// axios 默认实例
 export const axiosInstance: AxiosInstance = globalAxios;
 
 // 这里可以配置 axios 更多选项 =========================================
@@ -85,7 +72,8 @@ axiosInstance.interceptors.request.use(
 			ElMessage.error(error);
 		}
 
-		// 这里编写请求错误代码
+		// 请求错误代码及自定义处理
+		ElMessage.error(error);
 
 		return Promise.reject(error);
 	}
@@ -109,15 +97,8 @@ axiosInstance.interceptors.response.use(
 		}
 
 		// 处理规范化结果错误
-		//  if (serve && serve.hasOwnProperty("errors") && serve.errors) {
-		//    throw new Error(JSON.stringify(serve.errors || "Request Error."));
-		//  }
-		if (serve && serve.code === 401) {
-			clearAccessTokens();
-		} else if (serve && serve.code !== 200) {
-			var error = JSON.stringify(serve.message);
-			ElMessage.error(error);
-			throw new Error(error);
+		if (serve && serve.hasOwnProperty('errors') && serve.errors) {
+			throw new Error(JSON.stringify(serve.errors || 'Request Error.'));
 		}
 
 		// 读取响应报文头 token 信息
@@ -134,7 +115,16 @@ axiosInstance.interceptors.response.use(
 			Local.set(refreshAccessTokenKey, refreshAccessToken);
 		}
 
-		// 这里编写响应拦截代码 =========================================
+		// 响应拦截及自定义处理
+		if (serve.code === 401) {
+			clearAccessTokens();
+		} else if (serve.code === undefined) {
+			return Promise.resolve(res);
+		} else if (serve.code !== 200) {
+			var error = JSON.stringify(serve.message);
+			ElMessage.error(error);
+			throw new Error(error);
+		}
 
 		return res;
 	},
@@ -146,7 +136,8 @@ axiosInstance.interceptors.response.use(
 			}
 		}
 
-		// 这里编写响应错误代码
+		// 响应错误代码及自定义处理
+		ElMessage.error(error);
 
 		return Promise.reject(error);
 	}

+ 41 - 0
vue-next-admin/src/utils/base64Conver.ts

@@ -0,0 +1,41 @@
+/**
+ * @description: base64 to blob
+ */
+export function dataURLtoBlob(base64Buf: string): Blob {
+  const arr = base64Buf.split(',');
+  const typeItem = arr[0];
+  const mime = typeItem.match(/:(.*?);/)![1];
+  const bstr = window.atob(arr[1]);
+  let n = bstr.length;
+  const u8arr = new Uint8Array(n);
+  while (n--) {
+    u8arr[n] = bstr.charCodeAt(n);
+  }
+  return new Blob([u8arr], { type: mime });
+}
+
+/**
+ * img url to base64
+ * @param url
+ */
+export function urlToBase64(url: string, mineType?: string): Promise<string> {
+  return new Promise((resolve, reject) => {
+    let canvas = document.createElement('CANVAS') as Nullable<HTMLCanvasElement>;
+    const ctx = canvas!.getContext('2d');
+
+    const img = new Image();
+    img.crossOrigin = '';
+    img.onload = function () {
+      if (!canvas || !ctx) {
+        return reject();
+      }
+      canvas.height = img.height;
+      canvas.width = img.width;
+      ctx.drawImage(img, 0, 0);
+      const dataURL = canvas.toDataURL(mineType || 'image/png');
+      canvas = null;
+      resolve(dataURL);
+    };
+    img.src = url;
+  });
+}

+ 97 - 0
vue-next-admin/src/utils/download.ts

@@ -0,0 +1,97 @@
+import { dataURLtoBlob, urlToBase64 } from './base64Conver';
+
+/**
+ * Download online pictures
+ * @param url
+ * @param filename
+ * @param mime
+ * @param bom
+ */
+export function downloadByOnlineUrl(url: string, filename: string, mime?: string, bom?: BlobPart) {
+	urlToBase64(url).then((base64) => {
+		downloadByBase64(base64, filename, mime, bom);
+	});
+}
+
+/**
+ * Download pictures based on base64
+ * @param buf
+ * @param filename
+ * @param mime
+ * @param bom
+ */
+export function downloadByBase64(buf: string, filename: string, mime?: string, bom?: BlobPart) {
+	const base64Buf = dataURLtoBlob(buf);
+	downloadByData(base64Buf, filename, mime, bom);
+}
+
+/**
+ * Download according to the background interface file stream
+ * @param {*} data
+ * @param {*} filename
+ * @param {*} mime
+ * @param {*} bom
+ */
+export function downloadByData(data: BlobPart, filename: string, mime?: string, bom?: BlobPart) {
+	const blobData = typeof bom !== 'undefined' ? [bom, data] : [data];
+	const blob = new Blob(blobData, { type: mime || 'application/octet-stream' });
+
+	const blobURL = window.URL.createObjectURL(blob);
+	const tempLink = document.createElement('a');
+	tempLink.style.display = 'none';
+	tempLink.href = blobURL;
+	tempLink.setAttribute('download', filename);
+	if (typeof tempLink.download === 'undefined') {
+		tempLink.setAttribute('target', '_blank');
+	}
+	document.body.appendChild(tempLink);
+	tempLink.click();
+	document.body.removeChild(tempLink);
+	window.URL.revokeObjectURL(blobURL);
+}
+
+/**
+ * Download file according to file address
+ * @param {*} sUrl
+ */
+export function downloadByUrl({ url, target = '_blank', fileName }: { url: string; target?: TargetContext; fileName?: string }): boolean {
+	const isChrome = window.navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
+	const isSafari = window.navigator.userAgent.toLowerCase().indexOf('safari') > -1;
+
+	if (/(iP)/g.test(window.navigator.userAgent)) {
+		console.error('Your browser does not support download!');
+		return false;
+	}
+	if (isChrome || isSafari) {
+		const link = document.createElement('a');
+		link.href = url;
+		link.target = target;
+
+		if (link.download !== undefined) {
+			link.download = fileName || url.substring(url.lastIndexOf('/') + 1, url.length);
+		}
+
+		if (document.createEvent) {
+			const e = document.createEvent('MouseEvents');
+			e.initEvent('click', true, true);
+			link.dispatchEvent(e);
+			return true;
+		}
+	}
+	if (url.indexOf('?') === -1) {
+		url += '?download';
+	}
+
+	openWindow(url, { target });
+	return true;
+}
+
+export function openWindow(url: string, opt?: { target?: TargetContext | string; noopener?: boolean; noreferrer?: boolean }) {
+	const { target = '__blank', noopener = true, noreferrer = true } = opt || {};
+	const feature: string[] = [];
+
+	noopener && feature.push('noopener=yes');
+	noreferrer && feature.push('noreferrer=yes');
+
+	window.open(url, target, feature.join(','));
+}

+ 241 - 0
vue-next-admin/src/views/system/file/index.vue

@@ -0,0 +1,241 @@
+<template>
+	<div class="sys-file-container">
+		<el-card shadow="hover" :body-style="{ paddingBottom: '0' }">
+			<el-form :model="queryParams" ref="queryForm" :inline="true">
+				<el-form-item label="文件名称" prop="fileName">
+					<el-input placeholder="文件名称" clearable @keyup.enter="handleQuery" v-model="queryParams.fileName" />
+				</el-form-item>
+				<el-form-item label="开始时间" prop="name">
+					<el-date-picker v-model="queryParams.startTime" type="datetime" placeholder="开始时间"
+						:shortcuts="shortcuts" />
+				</el-form-item>
+				<el-form-item label="结束时间" prop="code">
+					<el-date-picker v-model="queryParams.endTime" type="datetime" placeholder="结束时间"
+						:shortcuts="shortcuts" />
+				</el-form-item>
+				<el-form-item>
+					<el-button icon="ele-Refresh" @click="resetQuery">重置
+					</el-button>
+					<el-button type="primary" icon="ele-Search" @click="handleQuery">查询
+					</el-button>
+					<el-button icon="ele-UploadFilled" @click="openUploadDialog">上传
+					</el-button>
+				</el-form-item>
+			</el-form>
+		</el-card>
+
+		<el-card shadow="hover" style="margin-top: 8px;">
+			<el-table :data="fileData" style="width: 100%" v-loading="loading" border>
+				<el-table-column type="index" label="序号" width="55" align="center" />
+				<el-table-column prop="fileName" label="名称" show-overflow-tooltip></el-table-column>
+				<el-table-column prop="suffix" label="后缀" align="center" show-overflow-tooltip>
+					<template #default="scope">
+						<el-tag round>{{ scope.row.suffix }}</el-tag>
+					</template>
+				</el-table-column>
+				<el-table-column prop="sizeKb" label="大小kb" align="center" show-overflow-tooltip>
+				</el-table-column>
+				<el-table-column prop="url" label="预览" align="center" show-overflow-tooltip>
+					<template #default="scope">
+						<el-image style="width: 60px; height: 60px" :src="scope.row.url" :lazy="true"
+							:hide-on-click-modal="true" :preview-src-list="[scope.row.url]" :initial-index="0"
+							:z-index=10000 fit="scale-down" />
+					</template>
+				</el-table-column>
+				<el-table-column prop="bucketName" label="存储位置" align="center" show-overflow-tooltip>
+				</el-table-column>
+				<el-table-column prop="id" label="存储标识" align="center" show-overflow-tooltip></el-table-column>
+				<!-- <el-table-column prop="userName" label="上传者" align="center" show-overflow-tooltip></el-table-column> -->
+				<el-table-column prop="createTime" label="创建时间" align="center" show-overflow-tooltip></el-table-column>
+				<el-table-column label="操作" width="140" fixed="right" align="center" show-overflow-tooltip>
+					<template #default="scope">
+						<el-button icon="ele-Download" size="small" text type="primary"
+							@click="downloadFile(scope.row)">
+							下载
+						</el-button>
+						<el-button icon="ele-Delete" size="small" text type="primary" @click="delFile(scope.row)">
+							删除
+						</el-button>
+					</template>
+				</el-table-column>
+			</el-table>
+			<el-pagination v-model:currentPage="tableParams.page" v-model:page-size="tableParams.pageSize"
+				:total="tableParams.total" :page-sizes="[10, 20, 50, 100]" small background
+				@size-change="handleSizeChange" @current-change="handleCurrentChange"
+				layout="total, sizes, prev, pager, next, jumper" />
+		</el-card>
+
+		<el-dialog title="上传文件" v-model="dialogVisible" :lock-scroll="false" width="400px">
+			<div>
+				<el-upload ref="uploadRef" drag :auto-upload="false" :limit="1" :file-list="fileList" action=""
+					:on-change="handleChange" accept=".jpg,.png,.bmp,.gif,.txt,.pdf,.xlsx,.docx">
+					<el-icon class="el-icon--upload">
+						<ele-UploadFilled />
+					</el-icon>
+					<div class="el-upload__text">
+						将文件拖到此处,或<em>点击上传</em>
+					</div>
+					<template #tip>
+						<div class="el-upload__tip">
+							请上传大小不超过 10MB 的文件
+						</div>
+					</template>
+				</el-upload>
+			</div>
+			<template #footer>
+				<span class="dialog-footer">
+					<el-button @click="dialogVisible = false">取消</el-button>
+					<el-button type="primary" @click="uploadFile">确定</el-button>
+				</span>
+			</template>
+		</el-dialog>
+	</div>
+</template>
+
+<script lang="ts">
+import { toRefs, reactive, onMounted, ref, defineComponent, onUnmounted, getCurrentInstance } from 'vue';
+import { ElMessageBox, ElMessage, UploadInstance } from 'element-plus';
+
+import { downloadByUrl } from '/@/utils/download';
+import { getAPI } from '/@/utils/axios-utils';
+import { SysFileApi } from '/@/api-services';
+
+export default defineComponent({
+	name: 'sysFile',
+	components: {},
+	setup() {
+		const { proxy } = getCurrentInstance() as any;
+		const uploadRef = ref<UploadInstance>()
+		const state = reactive({
+			loading: true,
+			fileData: [] as any,
+			queryParams: {
+				fileName: undefined,
+				startTime: undefined,
+				endTime: undefined,
+			},
+			tableParams: {
+				page: 1,
+				pageSize: 10,
+				total: 0 as any,
+			},
+			dialogVisible: false,
+			fileList: [] as any,
+		});
+		onMounted(async () => {
+			handleQuery();
+
+			proxy.mittBus.on("submitRefresh", () => {
+				handleQuery();
+			});
+		});
+		onUnmounted(() => {
+			proxy.mittBus.off("submitRefresh");
+		});
+
+		// 查询操作
+		const handleQuery = async () => {
+			if (state.queryParams.startTime == null) state.queryParams.startTime = undefined;
+			if (state.queryParams.endTime == null) state.queryParams.endTime = undefined;
+			state.loading = true;
+			var res = await getAPI(SysFileApi).sysFilePageGet(
+				state.queryParams.fileName,
+				state.queryParams.startTime,
+				state.queryParams.endTime,
+				state.tableParams.page,
+				state.tableParams.pageSize);
+			state.fileData = res.data.result?.items;
+			state.tableParams.total = res.data.result?.total;
+			state.loading = false;
+		};
+		// 重置操作
+		const resetQuery = () => {
+			state.queryParams.fileName = undefined;
+			state.queryParams.startTime = undefined;
+			state.queryParams.endTime = undefined;
+			handleQuery();
+		};
+		// 打开上传页面
+		const openUploadDialog = () => {
+			state.dialogVisible = true;
+		};
+		// 通过onChanne方法获得文件列表
+		const handleChange = (file: any, fileList: []) => {
+			state.fileList = fileList;
+		};
+		// 上传
+		const uploadFile = async () => {
+			if (state.fileList.length < 1) return;
+			await getAPI(SysFileApi).sysFileUploadPostForm(state.fileList[0].raw);
+			handleQuery();
+			ElMessage.success('上传成功');
+			state.dialogVisible = false;
+		}
+		// 下载
+		const downloadFile = async (row: any) => {
+			// var res = await getAPI(SysFileApi).sysFileDownloadPost({ id: row.id });
+			downloadByUrl({ url: row.url });
+		};
+		// 删除
+		const delFile = (row: any) => {
+			ElMessageBox.confirm(`确定删除文件:【${row.fileName}】?`, '提示', {
+				confirmButtonText: '确定',
+				cancelButtonText: '取消',
+				type: 'warning',
+			})
+				.then(async () => {
+					await getAPI(SysFileApi).sysFileDeletePost({ id: row.id });
+					handleQuery();
+					ElMessage.success('删除成功');
+				})
+				.catch(() => { });
+		};
+		// 分页改变
+		const handleSizeChange = (val: number) => {
+			state.tableParams.pageSize = val;
+			handleQuery();
+		};
+		// 分页改变
+		const handleCurrentChange = (val: number) => {
+			state.tableParams.page = val;
+			handleQuery();
+		};
+		const shortcuts = [
+			{
+				text: '今天',
+				value: new Date(),
+			},
+			{
+				text: '昨天',
+				value: () => {
+					const date = new Date();
+					date.setTime(date.getTime() - 3600 * 1000 * 24);
+					return date;
+				},
+			},
+			{
+				text: '上周',
+				value: () => {
+					const date = new Date();
+					date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
+					return date;
+				},
+			},
+		];
+		return {
+			handleQuery,
+			resetQuery,
+			uploadRef,
+			openUploadDialog,
+			handleChange,
+			uploadFile,
+			downloadFile,
+			delFile,
+			handleSizeChange,
+			handleCurrentChange,
+			shortcuts,
+			...toRefs(state),
+		};
+	},
+});
+</script>

+ 2 - 2
vue-next-admin/src/views/system/server/index.vue

@@ -96,7 +96,7 @@
       <el-table :data="machineDiskInfo" style="width: 100%">
         <el-table-column prop="diskName" label="盘符">
           <template #default="scope">
-            <el-tag round> {{ scope.row.diskName }}</el-tag>
+            <el-tag round>{{ scope.row.diskName }}</el-tag>
           </template>
         </el-table-column>
         <el-table-column prop="typeName" label="类型" />
@@ -111,7 +111,7 @@
         </el-table-column>
         <el-table-column prop="availablePercent" label="使用率">
           <template #default="scope">
-            <el-tag> {{ scope.row.availablePercent }}%</el-tag>
+            <el-tag>{{ scope.row.availablePercent }}%</el-tag>
           </template>
         </el-table-column>
       </el-table>