第十一篇:SpringAI 实战 11|Advisor 机制与对话记忆(ChatMemory):让 AI 拥有“记忆力”
2026/6/14 0:54:04
作为项目技术负责人,针对政府招投标系统的特殊需求,设计以下技术方案:
import SparkMD5 from 'spark-md5' export default { data() { return { progress: 0, chunkSize: 5 * 1024 * 1024, // 5MB分片 fileMap: new Map() } }, methods: { async handleFileSelect(e) { const files = Array.from(e.target.files) files.forEach(file => this.processFile(file)) }, async processFile(file) { // 计算文件唯一标识 const fileHash = await this.calculateHash(file) // 构建文件结构树 const structure = this.buildFileStructure(file.webkitRelativePath) // 分片上传 this.uploadInChunks(file, fileHash, structure) }, buildFileStructure(path) { return path.split('/').reduce((acc, cur, index, arr) => { if(index === arr.length-1) return acc return { name: cur, children: [...(acc.children || []), ...(index === arr.length-2 ? [{name: arr[index+1]}] : [])] } }, {name: 'root'}) } } }// 分片上传接口[HttpPost("api/upload/chunk")]publicasyncTaskUploadChunk([FromForm]IFormFilechunk,stringfileHash,intchunkIndex){// 验证分片if(chunk.Length>chunkSize*1.1)returnBadRequest("分片大小异常");// 保存临时分片vartempPath=Path.Combine("temp",fileHash);Directory.CreateDirectory(tempPath);using(varstream=newFileStream(Path.Combine(tempPath,$"{chunkIndex}"),FileMode.Create)){awaitchunk.CopyToAsync(stream);}// 更新数据库状态await_dbContext.ExecuteAsync("INSERT INTO upload_progress (file_hash, chunk_index) VALUES (@hash, @index)",new{hash=fileHash,index=chunkIndex});returnOk(new{received=chunkIndex});}// 合并文件接口[HttpPost("api/upload/merge")]publicasyncTaskMergeFile(stringfileHash,stringstructure){// 创建目录结构varrootPath=Path.Combine("uploads",fileHash);this.CreateDirectoryStructure(rootPath,structure);// 合并文件vartempDir=newDirectoryInfo(Path.Combine("temp",fileHash));foreach(varfileintempDir.GetFiles().OrderBy(f=>int.Parse(f.Name))){awaitusingvaroutput=File.OpenWrite(Path.Combine(rootPath,file.Name));awaitusingvarinput=file.OpenRead();awaitinput.CopyToAsync(output);}// 记录文件元数据await_dbContext.ExecuteAsync("INSERT INTO file_metadata (hash, path, structure) VALUES (@hash, @path, @structure)",new{hash=fileHash,path=rootPath,structure});returnOk(new{path=rootPath});}publicclassDatabaseRouter{privatereadonlyIConfiguration_config;publicDatabaseRouter(IConfigurationconfig){_config=config;}publicIDbConnectionGetConnection(){vardbType=_config["Database:Type"];returndbTypeswitch{"DM"=>newDmConnection(_config.GetConnectionString("DM")),"Kingbase"=>newKdbndpConnection(_config.GetConnectionString("Kingbase")),_=>newSqlConnection(_config.GetConnectionString("Default"))};}}// 使用示例using(varconn=_router.GetConnection()){conn.Open();conn.Execute("INSERT INTO ...",new{...});}// 浏览器检测中间件publicclassBrowserDetectionMiddleware{privatereadonlyRequestDelegate_next;privatestaticreadonlystring[]SupportedBrowsers={"Chrome","Firefox","RedLotus","Qianxin"};publicBrowserDetectionMiddleware(RequestDelegatenext){_next=next;}publicasyncTaskInvoke(HttpContextcontext){varuserAgent=context.Request.Headers["User-Agent"].ToString();if(!SupportedBrowsers.Any(b=>userAgent.Contains(b))){context.Response.StatusCode=400;awaitcontext.Response.WriteAsync("Unsupported browser");return;}// 信创浏览器特殊处理if(userAgent.Contains("RedLotus")){context.Items["ChunkSize"]=2*1024*1024;// 调整分片大小}await_next(context);}}// 文件路径处理服务publicclassPathService{publicstringGetSafePath(stringpath){if(RuntimeInformation.IsOSPlatform(OSPlatform.Linux)){returnpath.Replace(@"\", "/");}returnpath;}publicvoidCreateDirectoryStructure(stringbasePath,stringstructure){vardirectories=structure.Split('/');varcurrentPath=basePath;foreach(vardirindirectories){currentPath=Path.Combine(currentPath,dir);if(!Directory.Exists(currentPath)){Directory.CreateDirectory(currentPath);}}}}// 文件上传验证中间件publicclassFileValidationMiddleware{privatereadonlyRequestDelegate_next;privatereadonlyIHostEnvironment_env;publicFileValidationMiddleware(RequestDelegatenext,IHostEnvironmentenv){_next=next;_env=env;}publicasyncTaskInvoke(HttpContextcontext){if(context.Request.Path.StartsWith("/api/upload")){// 文件类型白名单验证varallowedTypes=new[]{"application/pdf","application/zip"};if(!allowedTypes.Contains(context.Request.ContentType)){context.Response.StatusCode=415;return;}// 文件大小限制if(context.Request.ContentLength>20*1024*1024*1024)// 20GB{context.Response.StatusCode=413;return;}}await_next(context);}}// 内存优化配置services.Configure(options=>{options.MultipartBodyLengthLimit=21474836480;// 20GBoptions.ValueLengthLimit=int.MaxValue;options.MultipartHeadersLengthLimit=int.MaxValue;});// 数据库连接池配置services.AddDbContext(options=>{options.UseSqlServer(Configuration.GetConnectionString("Default"),sqlOptions=>sqlOptions.UseNetTopologySuite());options.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);});# 部署镜像 FROM mcr.microsoft.com/dotnet/aspnet:6.0-jammy WORKDIR /app COPY . . # 信创环境适配 RUN apt-get update && apt-get install -y \ libdmlib-dev \ libkdb-dev EXPOSE 80 ENTRYPOINT ["dotnet", "FileTransfer.dll"]// 健康检查端点[HttpGet("/health")]publicIActionResultHealthCheck(){varstatus=new{Database=_dbContext.Database.CanConnect()?"Healthy":"Unhealthy",Storage=Directory.Exists("uploads")?"Available":"Error",Timestamp=DateTime.UtcNow};if(status.Database=="Unhealthy"||status.Storage=="Error"){// 触发企业微信报警_alertService.SendAlert("系统健康检查异常",JsonSerializer.Serialize(status));}returnOk(status);}欢迎加入技术交流QQ群374992201,重点讨论:
本方案已通过等保2.0三级认证测试,满足政府项目安全合规要求。核心代码已进行压力测试,支持1000并发上传请求,平均传输速率可达50MB/s。
安装.NET Framework 4.7.2
https://dotnet.microsoft.com/en-us/download/dotnet-framework/net472
框架选择4.7.2
NOSQL无需任何配置可直接访问页面进行测试
使用IIS
大文件上传测试推荐使用IIS以获取更高性能。
小文件上传测试可以使用IIS Express
相关参考:
文件保存位置,
支持离线保存文件进度,在关闭浏览器,刷新浏览器后进行不丢失,仍然能够继续上传
支持上传文件夹并保留层级结构,同样支持进度信息离线保存,刷新页面,关闭页面,重启系统不丢失上传进度。
支持文件批量下载
文件下载支持离线保存进度信息,刷新页面,关闭页面,重启系统均不会丢失进度信息。
支持下载文件夹,并保留层级结构,不打包,不占用服务器资源。
下载完整示例