【问题标题】:Zip file is not getting downloaded using asp.net未使用 asp.net 下载 Zip 文件
【发布时间】:2017-07-27 22:26:17
【问题描述】:

我有一个文件夹,其中有 3-4 pdf 文件。所以点击按钮时,我想将 PDF 文件下载为ZIP 文件。为此,我编写了以下代码

string strFilePath = HttpContext.Current.Server.MapPath("~/UploadedFiles/" + SAP_ID + '_' + CANDIDATEID + "\\" + SAP_ID + '_' + CANDIDATEID + ".pdf");
string strDirectory = HttpContext.Current.Server.MapPath("~/UploadedFiles/" + SAP_ID + '_' + CANDIDATEID);

HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);

if (Directory.Exists(strDirectory))
{
    if (File.Exists(strFilePath + ".zip"))
    {
        var filestream = new System.IO.FileStream(strFilePath + ".zip", System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
        filestream.Close();
        File.Delete(strFilePath + ".zip");
     }                   
}

//  ZipFile.CreateFromDirectory(strDirectory, strDirectory + ".zip");

var stream = new FileStream(strDirectory + ".zip", FileMode.Open);

result.Content = new StreamContent(stream);
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = Path.GetFileName(strDirectory + ".zip");
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentLength = stream.Length;

但是点击按钮时,ZIP 没有被下载,浏览器只是加载。

请帮我看看是什么原因?

【问题讨论】:

  • 你能检查一下zip文件是否是在服务器上创建的吗?
  • @minhhn2910:好的,让我检查一下!
  • @minhhn2910:不,现在当我调试我的代码时,在var stream = new FileStream(strDirectory + ".zip", FileMode.Open); 行出现{"Could not find file 'D:\\UserName\\VSATFINAL_353\\VSATTSSRSurvey\\UploadedFiles\\I-BR-RNCH-ENB-0243_C3.zip'. 错误
  • @minhhn2910: 抱歉,实际上它是在这一行创建的 ZipFile.CreateFromDirectory(strDirectory, strDirectory + ".zip"); 我注释掉了那一行。但是当它已经存在时,它会给我带来错误。那我该怎么办呢?
  • 您使用的是 MVC 还是 Web 表单?如果您使用的是 MVC,请尝试 FileResult 或对于 Web 表单,请尝试 Response.TransmitFile

标签: c# asp.net zip


【解决方案1】:

使用 Response.TransmitFile 方法可能更幸运,这里是一个使用 zip 文件地址的示例 -

Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition", "attachment; filename=file.zip");
Response.TransmitFile(strFilePath + ".zip");
Response.Flush();

【讨论】:

  • 让我试试看能不能弄到
  • HttpContext.Current.Response.TransmitFile(strDirectory + ".zip"); 行收到此错误The process cannot access the file 'D:\UserName\VSATFINAL_353\VSATTSSRSurvey\UploadedFiles\I-MH-CLSG-ENB-0001_C3.zip' because it is being used by another process.
  • 你有没有关闭的文件流?我注意到你有几行现在是多余的 - var stream = new FileStream(strDirectory + ".zip", FileMode.Open); result.Content = new StreamContent(stream);
  • 可能是,这是我的全部功能。请让我知道我可以删除不需要的代码。 dotnetfiddle.net/DQChgv
  • 删除第223行和第235行,这些是打开不需要的文件流,会导致上述错误
【解决方案2】:

如果未创建 zip 文件,您可能需要将 UploadedFiles 目录的写入/修改权限授予 IIS AppPool\yourAppPoolName 。

【讨论】:

  • 嘿,正在创建 Zip 文件但没有下载
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-22
  • 2015-10-18
  • 2020-10-26
  • 1970-01-01
相关资源
最近更新 更多