The POST response I received was garbled and corrupted

Operating under the name DownloadZipFile, my service compiles data and constructs a Zip file for easy downloading. This particular service provides a response that contains the stream leading to the file.

A Glimpse of the Service:

[HttpPost]
public ActionResult DownloadZipFile(string zipData)
{
    try
    {
        // Create the Zip File.
        using (MemoryStream zipStream = DownloadHelper.BuildZipFileData(zipData))
        {
            // Construct the response with 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 any errors encountered.
        _logService.Error(LogHelper.GetWebRequestInfo(ControllerContext.HttpContext.Request), e);
    }
}

The download and opening of the zip file occurs seamlessly when employing this service in the following manner:

Call to the Service #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();

However, utilizing an AJAX Post call yields larger file sizes than expected when converting the response to a blob.

Engage the Service with Call #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;
             }
         }
     });

Despite externing Service Call #2, the generated Zip File arrives corrupted.

Could it be due to encoding discrepancies? A comparison between the correct and erroneous Zip Files display distinct patterns:

Intact Zip:

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

Malfunctioning Zip:

PK ￿￿￿g ￿ BOM.csvu￿￿￿E￿￿+￿￿/￿￿W￿H[￿4Iզ| >￿_￿(-￿l￿,￿;w￿￿￿m^ֳ￿kU￿t￿6)￿Zjqz"0dҳ￿yd#￿3֘R￿￿k￿MY￿2'￿￿ɽd￿O￿"BX￿￿￿,￿ ￿￿￿￿￿￿￿A￿VG ]3

Evidently, the files have undergone differing forms of encoding. How should we approach this dilemma?

Answer №1

Appreciation to Musa for the helpful hint provided.

Presenting the Service Call utilized for downloading the Zip File:

Initiating Service Call #1

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

                // verifying filename presence
                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); // cleaning up
                }
            } else {

   // Proceed with Error Handling
            }
        }
    }

    // Opening HTTP Request and Executing 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)));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Do not refresh the ajax content

I'm using Ajax to dynamically load HTML content into a div container. The content is loaded when an element with the class "link" is clicked, as shown below: $(".link").click(function () { $('.link').removeClass('current'); ...

Using nodeJS to showcase content on a web page

I'm relatively new to NodeJS, and I am trying to figure out if there is a way to utilize NodeJS similar to JavaScript. My goal is to retrieve data from a database and display it within a div on my index.html page. When attempting to use querySelector, ...

Shuffle math calculations involving subtraction by a percentage using node.js or JavaScript

Hello there! If you want to subtract, say 35%, from a number, you can use methods like this: var valueInString = "2383"; var num = parseFloat(valueInString); var val = num - (num * .35); console.log(val); But have you ever wondered how you could randomiz ...

Having trouble with the import of the directory's index file?

The code snippet in application.js indicates that the "home" imported from "./routes/index" is undefined. import {home} from "./routes/index" console.log(JSON.stringify(home, null, 4)) This is what index.js contains: export * from "./home.js" And here ...

An error has arisen while organizing a collection of short elements: 'There is a discrepancy.'

I am facing an issue with my C++ struct: typedef struct FormulaSyntax{ WORD StructSize; short formulaSyntax [2]; } FormulaSyntax; The problem arises when I try to pass an instance of this struct to a DLL method in C#. Here is my a ...

decide whether to use webpack bundling during development or not

Whenever I save a file, it takes around 30 seconds for the changes to reflect. I am currently using gulp watch and webpack for bundling around a hundred files. Is there any way to speed up the build process? ...

Execute a PHP class method using AJAX

Here is an example of what I am trying to achieve: class testing { function execute(){ perform action; } } I am looking to use ajax to determine if a specific button has been clicked: echo "<button name=\"updateList\" type=\"butto ...

Error message when trying to get tree from Json using jqTree: "Oops! $(...).tree is not a valid function."

Currently, I am utilizing jqTree to display JSON data in a tree format. However, as I was implementing the demo of jqTree, an error occurred: "Uncaught TypeError: $(...).tree is not a function" ...

Anticipated that the absence of a value would match the presence of an Object

Struggling with running AngularJS unit tests for $resource using Jasmine v2.0 and Karma v0.13, I managed to convert custom actions to newer syntax successfully. However, a specific type of test is giving me trouble, which I suspect is related to $httpBacke ...

Using curly braces when invoking a function from HTML within a Vue.js application

When I call a function, for example on click, it works whether or not I use curly braces. However, I have created a function that triggers a custom event from a child component. I then await this event in a parent component and update the state with my par ...

Porting the C# .Net compact framework to the Linux platform

We currently have a legacy application built using C# .Net compact framework that is running on Windows CE. Is it possible to port this application to run on a Linux platform? If so, what tools and steps would be necessary to successfully complete the por ...

The process of running npx create-react-app with a specific name suddenly halts at a particular stage

Throughout my experience, I have never encountered this particular issue with the reliable old create-react-app However, on this occasion, I decided to use npx create-react-app to initiate a new react app. Below is a screenshot depicting the progress o ...

Shifting elements within Phoria.js

I'm currently working on a game where a ball bounces and falls into a randomly placed bin. I'm wondering if there's a way for the ball to jump and land based on the dynamic coordinates of the bin. If I have knowledge of the direction and dis ...

Ways to run evaluations on 'private' functions within an angular service using Karma and Jasmine

In my Angular application, I have a BracketService that consists of various functions for comparing weights and creating brackets based on weight groups. The service includes functions like compareByWeight, filterWeightGroup, and createBracketsByWeightGrou ...

What could be the reason for the Checkbox's value not showing up after making changes?

In my React and Material UI project, I am facing an issue where I want to check all checkboxes in a list by simply checking one checkbox in a parent component. Despite passing down the correct value of the parent checkbox through props, the visual changes ...

Submit a form utilizing jQuery's ajax function

I am currently facing an issue with my use of the $.ajax post method. My intention is to submit form data on the current page itself, but somehow the script is redirecting to the action page. If anyone could pinpoint what's causing this redirection ...

Guidelines for parsing a JSON response and retaining specific attributes

I am currently working on parsing the response from the following link: . My program is expected to receive a response like this: [ { "createdAt": "2015-06-15T13:10:43.000Z", "domain": "000.biz", " ...

Sending information from one ajax request to anotherORTransferring

Apologies for not including code in this post as I am currently working on a project in a car without internet access. Thankfully, I am using the amazing Stack Exchange app. Currently, I am facing a challenge where I need to work with two separate API cal ...

Is there anybody who can assist me with ${}?

Having an issue with using ${'variable'+i} in a loop function. The goal is to call each function from a loop. Explored template literals but couldn't find a solution for this specific problem. Desired format: ${'variable'+i} // (w ...

Tips for incorporating VueJS 2 global components within single file components

As I attempt to utilize a globally registered component (using Vue.component) within a single file component, I consistently encounter the following warning: vue.common.js:2611[Vue warn]: Unknown custom element: <my-component> - did you register the ...