2

我正在使用 c#.net 应用程序,我需要在其中使用 c# codebase 下载 zip 文件。我正在使用以下代码下载文件:

Response.ContentType = "application/zip"                       
Response.AppendHeader("Content-Disposition", string.Format("attachment; filename = {0}", System.IO.Path.GetFileName(sZipFileName)));
Response.TransmitFile(sZipFilePath);
HttpContext.Current.ApplicationInstance.CompleteRequest();

zip 文件已传输,但是当我在下载后尝试打开 zip 文件时,我收到一条错误消息“无法打开文件:文件看起来不是有效的存档”

请让我知道我在哪里做错了,以及如何获取一个 zip 文件并在没有任何错误的情况下提取它。

提前致谢

4

8 回答 8

5

我不确定你的代码段为什么不起作用,但这里有一些代码我用来在我的应用程序中做同样的事情。希望能帮助到你。

var updateFile = new FileInfo("path/to/file");
Response.ContentType = "application/octet-stream";
Response.AddHeader("content-disposition", "attachment;filename=\"" + Path.GetFileName(updateFile.FullName) + "\"");
Response.AddHeader("content-length", updateFile.Length.ToString());
Response.TransmitFile(updateFile.FullName);
Response.Flush();
于 2011-02-04T13:36:07.040 回答
1

尝试Response.End()在脚本末尾添加。

于 2011-02-04T13:41:46.053 回答
0

你是在服务器上压缩文件,还是下载已经压缩的文件?如果您使用的是 jscript,我认为返回压缩的文件会有问题。如果不是,那么您没有正确返回正在压缩的文件名。

我也这样做过,制作压缩文件然后下载。我使用了 c#、jscript 和 asp.net。

它对我来说很完美。我将文件/文件传递给 jscript 文件,然后 jscript 调用一个方法来压缩文件,当在服务器上完成压缩时,服务器将其返回给客户端并自动开始下载。

于 2011-02-04T14:11:11.873 回答
0

我已经测试了流动的代码并且它可以工作,所以分享它。我做的一件强制性的事情是使用“ Response.Flush();”。

private void DownloadCandidateDocument()
{
    Response.Clear();
    Response.ClearContent();
    Response.ClearHeaders();
    var buffer = new byte[] {};

    buffer = get you byte array here from service or file system

    if (buffer.Length > 0)
    {
        Response.ContentType = "application/zip";
        Response.BinaryWrite(buffer);

        var fileName = "myzipfile";
        Response.AddHeader("content-disposition",
            string.Format(@"attachment;filename=""{0}""", fileName));

        Response.Flush();    
    }
}
于 2013-12-12T23:07:11.963 回答
0

试试Response.WriteFile(sZipFilePath);

于 2011-02-04T13:35:39.493 回答
0

我不知道您使用的是什么机器……但是在 Vista 之前的 Windows 版本对 zip 文件使用 FAt32 编码,而 Vista Microsft 开始使用 NTFS 作为文件格式。请检查您的存档文件格式,因为当用户使用 XP 操作系统并且我在 win7 中创建存档时,我遇到了非常相似的情况(错误消息与您发布的相同)。此致,

于 2011-09-12T16:08:28.717 回答
0

尝试:

HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("Content-Disposition", "inline; filename=" + "test.zip");
HttpContext.Current.Response.ContentType = "application/zip";
HttpContext.Current.Response.BinaryWrite(ba);
HttpContext.Current.Response.End();

其中 ba 是代表 zip 文件的字节数组

于 2011-02-04T13:38:56.450 回答
0

我正在使用这个:

Response.ContentType = "application/zip" ;
Response.AddHeader("content-disposition", "attachment; filename=" + HttpUtility.UrlEncode(System.IO.Path.GetFileName(path)));
Response.WriteFile(path);
Response.End();

其中变量路径是(本地)文件的完整路径

于 2011-02-04T13:39:39.953 回答