当前位置: 首页 > news >正文

NET8环境WebAPI实现文件的压缩及下载

目录

  • 1、文件下载的原理
  • 2、具体实现
    • 2.1 提前准备
    • 2.2 服务器端的实现
    • 2.3 请求端的实现
  • 3、代码下载
  • 4、更多特性
    • 4.1 单独压缩文件
    • 4.2 解析
      • 4.2.1 整体解析
      • 4.2.2 单个文件解析
    • 4.3 其他
      • 4.3.1 设置压缩级别
      • 4.3.2 密码保护
      • 4.3.3 进度反馈
  • 5、参考资料

1、文件下载的原理

在实际应用环境中,文件的下载是一个特别常见的需求。为了传输文件的大小,往往需要对文件进行压缩,因此就涉及到文件的压缩及文件的下载,具体步骤有5步。(1)、请求端发出文件的请求。这个可以根据实际需求,使用get/post及参数,发起一个请求。(2)、服务器收到请求后,会根据需求生成(或者准备)相关文件(最常用的例子就是:患者通过医院App下载处方、门诊记录单、诊断证明书之类)【这一步往往是偏向业务相关】。(3)然后将这些生成的文件,压缩成zip文件格式。(4)、服务端返回数据。(5)、客户端收到数据后,解析Response中的Stream,并使用FileStream将文件存储到本地。
具体的原理如下图所示
文件下载的原理

2、具体实现

2.1 提前准备

我们提前准备了文件(这步主要是模拟实际业务中生成的文件夹及文件)。在fhirs文件夹下有一个index.xml文件和emrfhirs文件夹,并且在emrfhirs文件夹内有001fhir.json002fhir.json003fhir.json三个文件。文档的目录结构如下:
在这里插入图片描述
在这里插入图片描述

2.2 服务器端的实现

创建webapi项目,实现下载文件的方法。具体代码如下

[HttpPost]
public async Task<ActionResult> getCompressionFile()
{try{/** 接收客户端的参数,本示例为了简化,不进行处理IFormCollection form = HttpContext.Request.Form;string? username = form["UserName"];string? password = form["Password"];string? remoteFilePath = form["RemotePath"];**/string source_folder = @"D:\data\fhirs"; //需要压缩的文件的路径,就是刚才上面提到的文件夹及文件string destination_path = @"D:\data\fhirsemr.zip";  //要将上面的文件夹变成的压缩文件// using System.IO.Compression;//将文件进行压缩await Task.Run(() =>{ZipFile.CreateFromDirectory(source_folder, destination_path);});//这个地方涉及一个知识//zip压缩文件,它的content-type是application/x-zip-compressed//rar压缩文件,它的content-type是application/octet-streamvar stream = new FileStream(destination_path, FileMode.Open, FileAccess.Read);return new FileStreamResult(stream, "application/x-zip-compressed"){FileDownloadName = "ermfile"};}catch (Exception ex){throw new Exception(ex.Message);}
}

上面就是服务端的代码

2.3 请求端的实现

客户端的请求端实现如下

//url:服务端的地址
//localFileFullPath:将文件存储到本地的路径
//otherParams:给业务使用的参数
private string GetFile(string url, string localFileFullPath, string otherParams)
{try{Uri uri = new Uri(url);HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);request.Method = "post"; //post、getrequest.ContentType = "application/x-www-form-urlencoded;charset=utf-8";request.KeepAlive = true;request.Credentials = CredentialCache.DefaultCredentials;using (Stream requestStream = request.GetRequestStream()){byte[] formDataBytes = Encoding.UTF8.GetBytes(otherParams);requestStream.Write(formDataBytes, 0, formDataBytes.Length);}HttpWebResponse response = (HttpWebResponse)request.GetResponse();//判断路径,并创建路径string path = Path.GetDirectoryName(localFileFullPath);if (!Directory.Exists(path) && !string.IsNullOrEmpty(path)){Directory.CreateDirectory(path);}//将文件using (FileStream fs = new FileStream(localFileFullPath, FileMode.Create, FileAccess.Write, FileShare.None)){using (Stream responseStream = response.GetResponseStream()){//创建本地文件写入流byte[] bArr = new byte[1024];int iTotalSize = 0;int size = responseStream.Read(bArr, 0, bArr.Length);while (size > 0){iTotalSize += size;fs.Write(bArr, 0, size);size = responseStream.Read(bArr, 0, bArr.Length);}}}return "Success-获取文件成功";}catch (Exception ex){return "Error-"+ex.Message;}
}

3、代码下载

代码比较简单,无代码

4、更多特性

4.1 单独压缩文件

如果你只想压缩特定的文件,而不是整个文件夹,你可以使用FileStream和ZipArchive来实现。实际上就是NET中的文件操作

using System.IO;
using System.IO.Compression;string startPath = @"c:\example\file.txt"; // 要压缩的文件路径
string zipPath = @"c:\example\result.zip"; // 压缩后的ZIP文件路径using (FileStream zipToOpen = new FileStream(zipPath, FileMode.Create))
{using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Create)){ZipArchiveEntry readmeEntry = archive.CreateEntry("file.txt");using (StreamWriter writer = new StreamWriter(readmeEntry.Open())){using (StreamReader reader = new StreamReader(startPath)){string content = reader.ReadToEnd();writer.Write(content);}}}
}

4.2 解析

4.2.1 整体解析

解压文件同样简单。我们可以使用ZipFile类的ExtractToDirectory方法来解压ZIP文件到指定文件夹:

using System.IO.Compression;string zipPath = @"c:\example\start.zip"; // 要解压的ZIP文件路径
string extractPath = @"c:\example\extract"; // 解压后的文件夹路径ZipFile.ExtractToDirectory(zipPath, extractPath);

这段代码会将start.zip文件解压到extract文件夹中。

4.2.2 单个文件解析

如果你需要更细粒度的控制,比如只解压ZIP文件中的特定文件,你可以使用ZipArchive来实现:

using System.IO;
using System.IO.Compression;string zipPath = @"c:\example\start.zip"; // 要解压的ZIP文件路径
string extractPath = @"c:\example\extract"; // 解压后的文件夹路径
string fileToExtract = "file.txt"; // 要解压的文件名using (ZipArchive archive = ZipFile.OpenRead(zipPath))
{ZipArchiveEntry entry = archive.GetEntry(fileToExtract);if (entry != null){string fullPath = Path.Combine(extractPath, entry.FullName);entry.ExtractToFile(fullPath, overwrite: true);}
}

这段代码会从start.zip文件中解压出file.txt文件到extract文件夹中

4.3 其他

4.3.1 设置压缩级别

在压缩文件时,你可以指定压缩级别来优化压缩效果。ZipArchiveMode.Create方法接受一个CompressionLevel枚举参数,允许你选择不同的压缩级别:

using (FileStream zipToOpen = new FileStream(zipPath, FileMode.Create))
{using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Create, true)){// ... 添加文件到ZIP归档中}
}

在这个例子中,第三个参数是布尔值,表示是否压缩归档中的条目。你也可以通过ZipArchiveEntry.CompressionLevel属性为单个条目设置压缩级别。

4.3.2 密码保护

.NETSystem.IO.Compression命名空间不支持为ZIP文件添加密码保护。如果你需要这个功能,你可能需要使用第三方库,如DotNetZip

4.3.3 进度反馈

在压缩或解压大文件时,提供进度反馈是一个很好的用户体验。然而,System.IO.Compression命名空间并没有直接提供进度反馈的机制。你可以通过计算处理的文件大小与总大小来估算进度,并使用例如IProgress<T>接口来报告进度。

5、参考资料

这篇文章主要参考了这篇文章:NET环境下使用原生方法实现文件压缩与解压

http://www.lryc.cn/news/421338.html

相关文章:

  • Ubuntu 18 使用NVIDIA上的HDMI输出声音
  • C#模拟量线性变换小程序
  • 跟《经济学人》学英文:2024年08月10日这期 How AI models are getting smarter
  • Spring Web MVC入门(上)
  • 【c++】公差判断函数 isInTolerance
  • 电脑新加的硬盘如何分区?新加硬盘分区选MBR还是GPT
  • 白骑士的Matlab教学基础篇 1.3 控制流
  • 设计模式 - 适配器模式
  • docker部署minIO
  • 「Pytorch」BF16 Mixed Precision Training
  • 论文阅读:Efficient Core Maintenance in Large Bipartite Graphs | SIGMOD 2024
  • LLMOps — 使用 BentoML 为 Llama-3 模型提供服务
  • 微软蓝屏事件揭秘:有问题的数据引发内存读取越界
  • NASA:北极ARCTAS差分吸收激光雷达(DIAL)遥感数据
  • Android 文件上传与下载
  • Java语言的充电桩系统Charging station system
  • RCE之无参数读取文件
  • Python GUI开发必看:Tkinter Button控件使用详解
  • 上海市计算机学会竞赛平台2024年7月月赛丙组得分排名
  • Can GPT-3 Perform Statutory Reasoning?
  • redis面试(十一)锁超时
  • C代码做底层及Matlab_SimuLink做应用层设计单片机程序
  • Cloud Kernel SIG 月度动态:ANCK OOT 驱动基线更新,发布 2 个 ANCK 版本
  • vue3仿飞书头像,根据不同名称生成不同的头像背景色
  • SpringBoot整合三方
  • React之组件的使用
  • 深度学习--长短期记忆网络
  • 研0 冲刺算法竞赛 day29 P2249 【深基13.例1】查找
  • 基于vue框架的CKD电子病历系统nfa2e(程序+源码+数据库+调试部署+开发环境)系统界面在最后面。
  • 笔记:python 安装tar包报错