0

我正在为 Sharepoint 编写一个应用程序,该应用程序在功能区上实现一个按钮,以将多个文件下载为 zip...

一切顺利,一切顺利……但是当我尝试使用 Chrome 或 Firefox 下载 zip 时,他们什么也没做……

我的代码是这样的:

private void WriteStreamToResponse(MemoryStream ms)
    {
        if (ms.Length > 0)
        {
            string filename = DateTime.Now.ToFileTime().ToString() + ".zip";
            Response.Clear();
            Response.ClearHeaders();
            Response.ClearContent();
            Response.ContentType = "application/zip"; //also tried application/octect and application/x-zip-compressed
            Response.AddHeader("Content-Length", ms.Length.ToString());
            Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);

            byte[] buffer = new byte[65536];
            ms.Position = 0;
            int num;
            do
            {
                num = ms.Read(buffer, 0, buffer.Length);
                Response.OutputStream.Write(buffer, 0, num);
            }

            while (num > 0);

            Response.Flush();
        }
    }
4

2 回答 2

1

删除 Content-Length 并在代码中使用 Flush() 然后 End() ,不要在代码末尾使用 Close() ,您可以在声明所有内容之前使用它。当您不知道文件类型将是什么时,通常使用八位字节流,因此如果您知道文件类型将是什么,请远离它。使用 application/zip 作为 Content-Disposition。

       string filename = DateTime.Now.ToFileTime().ToString() + ".zip";
        Response.Clear();
        Response.BufferOutput = false;
        Response.ClearHeaders();
        Response.ClearContent();
        Response.ContentType = "application/x-zip-compressed"; //also tried application/octect and application/x-zip-compressed         
        Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);

        byte[] buffer = new byte[65536];
        ms.Position = 0;
        int num;
        do
        {
            num = ms.Read(buffer, 0, buffer.Length);
            Response.OutputStream.Write(buffer, 0, num);
        }

        while (num > 0);

        Response.Flush();
        Response.End();
于 2014-10-23T13:18:45.407 回答
0

你试过Application/octet-stream作为 MIME 类型吗?

或者

private void WriteStreamToResponse(MemoryStream ms)
{
    if (ms.Length > 0)
    {
        byte[] byteArray = ms.ToArray();
        ms.Flush();
        ms.Close();

        string filename = DateTime.Now.ToFileTime().ToString() + ".zip";
        Response.BufferOutput = true;
        Response.Clear();
        Response.ClearHeaders();
        Response.ClearContent();
        Response.ContentType = "application/octet-stream";
        Response.AddHeader("Content-Length", ms.Length.ToString());
        Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);

        Response.BinaryWrite(byteArray);
        Response.End();

    }
}
于 2012-06-21T11:33:28.533 回答