简体   繁体   English

从 web api 返回 zip 文件

[英]Returning a zipfile from a web api

I have built an asp net web api.我已经建立了一个asp网web api。 I need to return a zipfile, as a result of some inner logic.由于某些内部逻辑,我需要返回一个 zipfile。 I'm using this code and it works, but the resulting zip file, when unzipped manually, gave me this error "There are data after the end of the payload"我正在使用此代码并且它有效,但是生成的 zip 文件在手动解压缩时给了我这个错误“有效负载结束后有数据”

 using (ZipFile zip = new ZipFile())
 {
     ...
     zip.Save(di.FullName + "\\" + "Update.zip");
 }


 string path = Path.Combine(Properties.Settings.Default.PathDisposizioniHTML, "Update.zip");

 var response = new HttpResponseMessage(HttpStatusCode.OK);
 var stream = new System.IO.FileStream(path, System.IO.FileMode.Open);
 response.Content = new StreamContent(stream);
 response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");

This is how i receive the data in a .net console application:这就是我在 .net 控制台应用程序中接收数据的方式:

using (Stream output = File.OpenWrite(@"C:\prova\MyFile.zip"))
    using (Stream input = httpResponse.GetResponseStream())
    {
        input.CopyTo(output);
    }

If you already have the zip file on your system, you shouldn't need to do anything special before sending it as a response.如果您的系统上已经有 zip 文件,则在将其作为响应发送之前不需要做任何特别的事情。

This should work:这应该有效:

string filePath = @"C:\myfolder\myfile.zip";

return File(filePath, "application/zip");

If you're making the file on the fly, ie getting other files and programatically putting them into a zip file for the user, the following should work:如果您正在即时制作文件,即获取其他文件并以编程方式将它们放入用户的 zip 文件中,则以下内容应该有效:

public IActionResult GetZipFile(){

   //location of the file you want to compress
   string filePath = @"C:\myfolder\myfile.ext";

   //name of the zip file you will be creating
   string zipFileName = "zipFile.zip";

   byte[] result;


   using (MemoryStream zipArchiveMemoryStream = new MemoryStream())
   {
       using (ZipArchive zipArchive = new ZipArchive(zipArchiveMemoryStream, ZipArchiveMode.Create, true))
       {
           ZipArchiveEntry zipEntry = zipArchive.CreateEntry(zipFileName);
           using (Stream entryStream = zipEntry.Open())
           {
               using (MemoryStream tmpMemory = new MemoryStream(System.IO.File.ReadAllBytes(filePath)))
               {
                    tmpMemory.CopyTo(entryStream);
                };
           }
       }

       zipArchiveMemoryStream.Seek(0, SeekOrigin.Begin);
       result = zipArchiveMemoryStream.ToArray();
   }

   return File(result, "application/zip", zipFileName);

}

This is taken from a recent ASP.NET project of my own.这取自我自己最近的一个 ASP.NET 项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM