Jquery Ajax并下载动态创建的zip文件

时间:2015-12-08 17:03:41

标签: jquery .net

我使用下面的Jquery代码来调用asp.net表单后面的代码中定义的WebMethod来处理请求。传递的主要参数是DocUrls,它是一个包含所有Url文档的JSON字符串。

 $.ajax({
    type: "POST",
    url: "Default.aspx/ZipSearchResults",
    contentType: "application/json; charset=utf-8",
    data: "{'docUrls':" + JSON.stringify(checkIds) + "," +
            "'hostWeb':'" + hostWeb + "'}",
    success: function (response) {
        alert(response);

    },
    failure: function (xhr, status, error) {

        var err = eval("(" + xhr.responseText + ")");
        $('#example').text(err);
        $('#error').show();
    }
});

}

    [WebMethod]
    public static string ZipSearchResults(string[] docUrls, string hostWeb)
    {
        _logHelper.LogInfo("Downloading and Zipping files for selected files" + docUrls, _sessionId);


        HttpContext.Current.Response.SetCookie(new HttpCookie("fileDownload", "true") { Path = "/" });
        HttpContext.Current.Response.ClearContent();
        HttpContext.Current.Response.ClearHeaders();
        HttpContext.Current.Response.ContentType = "application/zip";
        HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=DyanmicZipFile.zip");

        byte[] buffer = new byte[4096];

        ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipOutputStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(HttpContext.Current.Response.OutputStream);
        zipOutputStream.SetLevel(0); //0-9, 9 being the highest level of compression
        zipOutputStream.UseZip64 = ICSharpCode.SharpZipLib.Zip.UseZip64.Off;

        var Web = new Uri(hostWeb);
        var context = HttpContext.Current;

        foreach (String fileNamePair in docUrls)
        {
            using (WebClient wc = new WebClient())
            {
                using (
                    var clientContext = TokenHelper.GetS2SClientContextWithWindowsIdentity(Web,
                        context.Request.LogonUserIdentity))
                {
                    wc.Credentials = System.Net.CredentialCache.DefaultCredentials;
                    using (Stream wcStream = wc.OpenRead(fileNamePair))
                    {
                        ICSharpCode.SharpZipLib.Zip.ZipEntry entry =
                            new ICSharpCode.SharpZipLib.Zip.ZipEntry(
                                ICSharpCode.SharpZipLib.Zip.ZipEntry.CleanName(fileNamePair));

                        zipOutputStream.PutNextEntry(entry);

                        int count = wcStream.Read(buffer, 0, buffer.Length);
                        while (count > 0)
                        {
                            zipOutputStream.Write(buffer, 0, count);
                            count = wcStream.Read(buffer, 0, buffer.Length);
                            if (!HttpContext.Current.Response.IsClientConnected)
                            {
                                break;
                            }
                            HttpContext.Current.Response.Flush();
                        }
                    }
                }
            }
        }
        zipOutputStream.Close();

        HttpContext.Current.Response.Flush();
        HttpContext.Current.Response.SuppressContent = true;  // Gets or sets a value indicating whether to send HTTP content to the client.
        HttpContext.Current.ApplicationInstance.CompleteRequest(); ;


        return "Success";
    }

返回的响应是垃圾,表明它是zip文件。如何下载zip文件?

请求

请求标题

Cache-Control:private
Content-Disposition:attachment; filename=DyanmicZipFile.zip
Content-Type:application/zip
Date:Tue, 08 Dec 2015 17:45:02 GMT
Persistent-Auth:true
Server:Microsoft-IIS/8.0
Transfer-Encoding:chunked
X-AspNet-Version:4.0.30319
X-Powered-By:ASP.NET
X-SourceFiles:=?UTF-8?B?RDpcU2FpXEJyYW5keXdpbmUuU1AuRUNNU2VhcmNoXEJyYW5keXdpbmUuU1AuRUNNU2VhcmNoV2ViXFBhZ2VzXERlZmF1bHQuYXNweFxaaXBTZWFyY2hSZXN1bHRz?=

响应

PK¡eGbhttp://xxxxxxx.xxxxxxxxx.com/sites/Clients/Migration%20Library/Formation/2811.pdfés%PDF-1.4
%¾ºÛî
1 0 obj
<</Type /Catalog/Pages 2 0 R/OpenAction 5 0 R/Metadata 62 0 R>>
endobj
2 0 obj
<</Type /Pages/Kids [ 3 0 R 8 0 R 10 0 R 12 0 R 14 0 R 16 0 R 21 0 R 23 0 R 25 0 R 27 0 R 29 0 R 31 0 R 33 0 R ]/Count 13>>
endobj
3 0 obj
<</Resources <</ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]/Font <</F1 6 0 R>>/XObject <</X1 7 0 R>>>>/Type /Page/MediaBox [ 0 0 612 792 ]/Parent 2 0 R/Rotate 0/Contents [ 36 0 R 37 0 R ]>>
endobj
4 0 obj
[ 3 0 R /XYZ 0 842 0 ]

2 个答案:

答案 0 :(得分:0)

首先,确保服务器返回正确的Content-Disposition标题:

Content-Disposition: attachement; filename.zip

以及正确的内容类型:

Content-Type: application/zip

我不确定jQuery是否能够处理结果,但文件应该自动下载。

你不能做&#34; saveFile&#34;在JavaScript中。它必须由服务器启动。

答案 1 :(得分:0)

唯一可行且可靠的选择是将zip文件保存到服务器并将URL传递给浏览器。这解决了我的问题!