c# - 如何从 Web API 2 HttpGet 发送 zip 文件

标签 c# zip ziparchive

我正在尝试弄清楚如何从给定的文件夹路径创建新的 zip 文件,并将其发送回发件人。

需要的是文件将被下载到请求它的发件人处。 我看过很多答案,但没有一个能帮助我找到确切的答案。

我的代码:

Guid folderGuid = Guid.NewGuid(); string folderToZip = ConfigurationManager.AppSettings["folderToZip"] + folderGuid.ToString();

Directory.CreateDirectory(folderToZip);

string directoryPath = ConfigurationManager.AppSettings["DirectoryPath"]; string combinedPath = Path.Combine(directoryPath, id);

DirectoryInfo di = new DirectoryInfo(combinedPath); 如果(di.Exists) { //提供要创建的 zip 文件的路径和名称 字符串 zipFile = folderToZip + "\"+ folderGuid + ".zip";

//call the ZipFile.CreateFromDirectory() method
ZipFile.CreateFromDirectory(combinedPath, zipFile, CompressionLevel.Fastest, true);

var result = new HttpResponseMessage(HttpStatusCode.OK);
using (ZipArchive zip = ZipFile.Open(zipFile, ZipArchiveMode.Read))
{
    zip.CreateEntryFromFile(folderFiles, "file.zip");
}

var stream = new FileStream(zipFile, FileMode.Open);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
    FileName = "file.zip"
};
log.Debug("END ExportFiles()");
return ResponseMessage(result);

最佳答案

在你的 Controller 中:

using System.IO.Compression.FileSystem; // Reference System.IO.Compression.FileSystem.dll

[HttpGet]
[Route("api/myzipfile"]
public dynamic DownloadZip([FromUri]string dirPath)
{
if(!System.IO.Directory.Exists(dirPath))
   return this.NotFound();

    var tempFile = System.IO.Path.Combine(System.IO.Path.GetTempPath(), Guid.NewGuid()); // might want to clean this up if there are a lot of downloads
    ZipFile.CreateFromDirectory(dirPath, tempFile);
    HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
    response.Content = new StreamContent(new FileStream(tempFile, FileMode.Open, FileAccess.Read));
    response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
    response.Content.Headers.ContentDisposition.FileName = fileName;
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");

  return response;
}

UPD:文件已存在的解决方法

关于c# - 如何从 Web API 2 HttpGet 发送 zip 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41333168/

相关文章:

c# - .Net Core 忽略环境变量 DOTNET_SKIP_FIRST_TIME_EXPERIENCE

python - 你将如何在 Python 中压缩未知数量的列表?

c# - 如何将文件写入内存流,压缩其中三个内存流,然后将其放入另一个内存流中?

c# - WPF TreeView 和虚拟化(UI 和数据)

c# - ASP.NET RequiredFieldValidator 不适用于 DropDownList Firefox 6

c# - 在 LINQ 查询中创建 DateTime

c# - 归档 zip 文件并将其保存到选择的位置,而不需要额外的文件路径?

R Shiny "R_ZIPCMD"路径压缩错误

Rust 帮助提取 ZIP 内容

php - 压缩存档: `failed to open stream: Is a directory`