从POST收到的响应已损坏

时间:2017-06-22 03:34:54

标签: javascript c# ajax post blob

我有一个名为DownloadZipFile的服务,用于整理数据,然后构建一个Zip文件以供下载。此服务返回包含文件流

的响应

服务:

[HttpPost]
public ActionResult DownloadZipFile(string zipData)
{
    try
    {
        // Create the Zip File.
        using (MemoryStream zipStream = DownloadHelper.BuildZipFileData(zipData))
        {
            // Build up the reponse including the file.
            HttpContext.Response.ClearContent();
            HttpContext.Response.ClearHeaders();
            HttpContext.Response.Clear();
            HttpContext.Response.Buffer = true;
            HttpContext.Response.ContentType = "application/zip";
            HttpContext.Response.AddHeader("Content-Disposition", "attachment; filename=MyZipFile.zip;");
            HttpContext.Response.BinaryWrite(zipStream.ToArray());
            HttpContext.Response.End();
        }
    }
    catch (Exception e)
    {
        // Log the error.
        _logService.Error(LogHelper.GetWebRequestInfo(ControllerContext.HttpContext.Request), e);
    }
 }

如果我这样调用这个服务,它会正确下载并打开zip文件。

服务电话#1

var form = $("<form></form>").attr('action', "DownloadZipFile").attr("method", "post");
form.append($("<input></input>").attr("type", "hidden").attr("name", "zipData").attr('value', escape(JSON.stringify(zipData))));
form.appendTo('body').submit().remove();

但是,如果我在将其从响应转换为blob时使用AJAX Post调用,则其大小远大于我发送的大小。

服务电话#2:

$.post("DownloadZipFile", { zipData: escape(JSON.stringify(zipData)) },
     function (data, status, response) {
         var filename = "";
         var disposition = response.getResponseHeader('Content-Disposition');
         if (disposition && disposition.indexOf('attachment') !== -1) {
             var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
             var matches = filenameRegex.exec(disposition);
             if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
         }

         var type = response.getResponseHeader('Content-Type');
         var blob = new Blob([data], { type: type });

         if (typeof window.navigator.msSaveBlob !== 'undefined') {
             window.navigator.msSaveBlob(blob, filename);
         } else {
             var URL = window.URL || window.webkitURL;
             var downloadUrl = URL.createObjectURL(blob);
             if (filename) {
                 var a = document.createElement("a");
                 if (typeof a.download === 'undefined') {
                     window.location = downloadUrl;
                 } else {
                     a.href = downloadUrl;
                     a.download = filename;
                     document.body.appendChild(a);
                     a.click();
                 }
             } else {
                 window.location = downloadUrl;
             }
         }
     });

使用服务呼叫#2,我得到的Zip文件已损坏

可能是编码吗?我检查了正确和不正确的Zip文件之间的数据,它们看起来像这样:

正确的邮编:

PKú,ÐJmÇ'¸g€BOM.csvu'ËNÃ0E÷HüÃ+ +ÆÑØy/>“WÔðH[Ä64IÕ| |&gt;‰_ÀN( - ¢l®,Ýã;wìÏ÷‡m ^Ö³ú 35VkUŽtÕf6)óºZcZjqz“0dÒ³ü9TÓ%yd#3Ö〜R>¡kÙMYæt2'Òâ|ɽdÈhO¶”BXÁ?ùÚ“Ç&lt;‰,ÖÍ'ååÎé ÁÝ!Ò²AVG] 3

损坏的邮编:

PKï¿¿ï¿¿ï¿¿ïï¿¿BOM.csvuï¿¿ï¿¿ï¿¿Eï¿¿ï¿¿+ï¿¿ï¿¿/ï¿¿ï¿¿Wï¿ ¿H [ï¿¿4IÕ||&GT;ï¿¿_ï¿¿(-ï¿¿lï¿¿,ï¿¿;wï¿¿ï¿¿ï¿¿m^ֳ￿kUï¿¿tï ¿¿6)ï¿¿Zjqz “0dҳ￿yd#ï¿¿3Ö~Rï¿¿ï¿¿kï¿¿MYï¿¿2'￿￿ɽdï¿¿Oï¿¿” BXï¿¿ï ¿¿ï¿¿,ï¿¿ï¿¿ï¿¿ï¿¿ï¿¿ï¿¿ï¿¿ï¿¿Aï¿¿VG] 3

似乎文件的编码方式不同。你们觉得怎么样?

1 个答案:

答案 0 :(得分:0)

谢谢穆萨给我的线索。

现在这是我用来下载我的Zip文件的服务电话:

服务电话#1

    var xhrq = new XMLHttpRequest();
    xhrq.onreadystatechange = function () {
        if (this.readyState == 4 ) {
            if (this.status == 200) {
                var xhrp = this;
                var response = this.response;

                // check for a filename
                var filename = "";
                var disposition = xhrp.getResponseHeader('Content-Disposition');
                if (disposition && disposition.indexOf('attachment') !== -1) {
                    var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
                    var matches = filenameRegex.exec(disposition);
                    if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
                }

                var type = xhrp.getResponseHeader('Content-Type');
                var blob = new Blob([response], { type: type, encoding: "UTF-8" });

                if (typeof window.navigator.msSaveBlob !== 'undefined') {
                    window.navigator.msSaveBlob(blob, filename);
                } else {
                    var URL = window.URL || window.webkitURL;
                    var downloadUrl = URL.createObjectURL(blob);

                    if (filename) {
                        var a = document.createElement("a");
                        if (typeof a.download === 'undefined') {
                            window.location = downloadUrl;
                        } else {
                            a.href = downloadUrl;
                            a.download = filename;
                            document.body.appendChild(a);
                            a.click();
                        }
                    } else {
                        window.location = downloadUrl;
                    }
                    setTimeout(function () { URL.revokeObjectURL(downloadUrl); }, 100); // cleanup
                }
            } else {

   // Call Back for Error
            }
        }
    }

    // Open HTTP Request and Call API Function
    xhrq.open("POST", appPath + "DownloadZipFile");
    xhrq.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    xhrq.responseType = 'blob';
    xhrq.send('designData=' + escape(JSON.stringify(zipData)));