简体   繁体   English

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

[英]Jquery Ajax and downloading dynamically created zip file

I am using the below Jquery code to call the WebMethod defined in the code behind of asp.net form to process the request. 我正在使用下面的Jquery代码来调用在asp.net表单后面的代码中定义的WebMethod来处理请求。 The main parameter being passed is the DocUrls which is a JSON string containing all Urls of documents. 传递的主要参数是DocUrls,它是包含所有Urls文档的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";
    }

The response being returned is all garbage indicating it to be zip file. 返回的响应都是垃圾,表明它是zip文件。 How do I go about downloading the zip file? 如何下载zip文件?

Request 请求

Request Headers 请求标题

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?=

Response 响应

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 ]

First, make sure that the server returns the proper Content-Disposition header: 首先,确保服务器返回正确的Content-Disposition标头:

Content-Disposition: attachement; filename.zip

As well as the proper Content-Type: 以及适当的Content-Type:

Content-Type: application/zip

I'm not sure if jQuery is going to be able to handle the result but the file should be downloading automatically. 我不确定jQuery是否能够处理结果,但是文件是否应该自动下载。

You cannot do a "saveFile" in JavaScript. 您无法在JavaScript中执行“ saveFile”。 It has to be initiated by the server. 它必须由服务器启动。

The only viable and reliable option was the save the zip file to the server and pass the url to the browser. 唯一可行和可靠的选择是将zip文件保存到服务器,并将URL传递给浏览器。 That fixed my issue! 那解决了我的问题!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM