【问题标题】:How to send a zip file from Web API 2 HttpGet如何从 Web API 2 HttpGet 发送 zip 文件
【发布时间】:2016-12-26 15:20:16
【问题描述】:

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

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

我的代码:

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

Directory.CreateDirectory(folderToZip);

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

DirectoryInfo di = new DirectoryInfo(combinedPath); 如果 (di.Exists) { //提供要创建的zip文件的路径和名称 string 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);

【问题讨论】:

  • 那么您的问题是关于如何创建 zip 文件或如何发送它?
  • 如何发送。
  • 如果你要发送一个 zip 文件,可能你需要一个 POST 命令而不是 GET,因为 GET 的请求大小是有限的。

标签: c# zipfile ziparchive


【解决方案1】:

在您的控制器中:

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:********\AppData\Local\Temp\tmp96C2.tmp'已经存在。
  • @o.Nassie 我更正了代码,对此表示歉意。
猜你喜欢
  • 2021-02-19
  • 2021-09-18
  • 2018-03-07
  • 2017-07-19
  • 2019-01-06
  • 1970-01-01
  • 2022-06-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多