ASP.NET创建zip文件以供下载:压缩的压缩文件夹无效或损坏

5rgfhyps  于 2023-07-01  发布在  .NET
关注(0)|答案(2)|浏览(116)
string fileName = "test.zip";
string path = "c:\\temp\\";
string fullPath = path + fileName;
FileInfo file = new FileInfo(fullPath);

Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.Buffer = true;
Response.AppendHeader("content-disposition", "attachment; filename=" + fileName);
Response.AppendHeader("content-length", file.Length.ToString());
Response.ContentType = "application/x-compressed";
Response.TransmitFile(fullPath);
Response.Flush();
Response.End();

实际的zip文件c:\temp\test.zip是好的,有效的,无论你想叫它什么。导航到目录c:\temp\并双击test.zip文件;它就会打开。
我的问题似乎只是与下载。上面的代码执行时没有任何问题。将显示文件下载对话框。我可以选择保存或打开。如果我尝试从对话框中打开文件,或保存它,然后打开它。我得到以下对话框消息:
压缩文件夹无效或已损坏。
对于Response.ContentType我尝试过:
application/x-compressed application/x-zip-compressed application/x-gzip-compresse application/octet-stream application/zip
zip文件是用一些先前的代码创建的(我确信由于我能够直接打开创建的文件,所以它工作得很好),使用:Ionic.zip
http://www.codeplex.com/DotNetZip

6yoyoihd

6yoyoihd1#

这一招奏效了。我不知道为什么,但它确实。

string fileName = "test.zip";
string path = "c:\\temp\\";
string fullPath = path + fileName;
FileInfo file = new FileInfo(fullPath);

Response.Clear();
//Response.ClearContent();
//Response.ClearHeaders();
//Response.Buffer = true;
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
//Response.AppendHeader("Content-Cength", file.Length.ToString());
Response.ContentType = "application/x-zip-compressed";
Response.WriteFile(fullPath);
//Response.Flush();
Response.End();
vltsax25

vltsax252#

当下载到客户端时,我喜欢使用这种方法。它将允许客户端选择他们希望下载文件的路径(请注意,某些浏览器不允许这样做):

System.IO.FileInfo file =
    new System.IO.FileInfo(filePath); // full file path, i.e: from disk to file
Response.ClearContent(); // just in case we remove (if any) written content
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/x-zip-compressed"; // compressed file type
Response.TransmitFile(file.FullName); // TransmitFile allows client to choose folder
Response.End();

相关问题