Get the Zip file content using PushStreamContent JavaScript

I am looking for the correct method to download a PushStreamContent within a Post request. I have already set up the backend request like this:

private static HttpClient Client { get; } = new HttpClient();
public HttpResponseMessage Get()
{

var filenamesAndUrls = new Dictionary<string, string>
{
    { 'README.md', 'https://raw.githubusercontent.com/StephenClearyExamples/AsyncDynamicZip/master/README.md' },
    { '.gitignore', 'https://raw.githubusercontent.com/StephenClearyExamples/AsyncDynamicZip/master/.gitignore'},
};

var result = new HttpResponseMessage(HttpStatusCode.OK)
{
    Content = new PushStreamContent(async (outputStream, httpContext, transportContext) =>
    {
        using (var zipStream = new ZipOutputStream(outputStream))
        {
            foreach (var kvp in filenamesAndUrls)
            {
                zipStream.PutNextEntry(kvp.Key);
                using (var stream = await Client.GetStreamAsync(kvp.Value))
                    await stream.CopyToAsync(zipStream);
            }
        }
    }),
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "MyZipfile.zip" };
return result;
}

In the frontend part, I used axios to send a Post request and created a blob from the result to download it (I made modifications to the backend to support Post). However, the download is taking too long and I believe that I am not utilizing PushStreamContent correctly. Perhaps I should consider using EventSource or something similar.

Thank you.

Answer №1

After spending some time searching, I have found two possible solutions:

  • Switch the download request from Post to Get.
  • Utilize Fetch instead of axios for the http request and send the response to the streamsaver package, which initiates instant downloads seamlessly.

Answer №2

Agreeing with houssem's suggestion of switching it to a get request.
As the creator of StreamSaver, I often search for people discussing it to offer assistance when needed. It is common for me to advise individuals to utilize the server for file saving instead of relying on StreamSaver. StreamSaver is specifically designed for client-generated content (ideal for applications like WebTorrent or webcam recording)


Downloads can only be initiated by navigating to the resource. This means that utilizing ajax methods (xhr, fetch, axios, etc) to trigger a download is not supported.
Using elements such as <a href>, <iframe>, location.href = all work effectively. If there is a requirement for a post request, submitting a <form> with application/multipart or URLEncoded is possible, but using JSON requests or other formats is not recommended. One limitation of this approach is the inability to include custom request headers, like an authentication header, unless added through a service worker. In such scenarios, sending cookies along with every request is a preferable solution.

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

Is there a way to extract all the data values starting with "data-" from the selected input fields in HTML5 and compile them into an object?

Looking for a way to automate input values: <input class="form" type="checkbox" name="item1" data-value="{ 'item1':'selected', 'price': 100 }" checked="checked"> <input class="form" type="checkbox" name="item2" data- ...

The Analog Clock is unable to access the property of null

I'm struggling to understand what's wrong here. The querySelector doesn't seem to be functioning correctly as I keep encountering the error "cannot read the property of null" on line 10 of my JavaScript code. const deg = 6; const hr = docum ...

Unable to send event from JavaScript to Component in Ionic

My goal is to notify a component that a script file has finished loading. My approach involves using the onload event of an element to dispatch an event. A service will then register an event listener for this event, waiting for clients to subscribe to an ...

How do I declare the links in my navigation drawer?

I have successfully implemented a navigation drawer with dropdown menus. However, I'm struggling to figure out how to declare the routes so that clicking on the navigation names redirects me to the desired route. Can you guide me on how to properly de ...

Replacing the tbody element in React with centered text using inline styles ---If you want

I am working with an empty array in React that I translate into state. When the array is empty, I want to insert a text that says "no match events yet..." into a react-bootstrap Table's tbody. In the current setup, I am struggling to center the text ...

Is there a way to switch the classList between various buttons using a single JavaScript function?

I'm currently developing a straightforward add to cart container that also has the ability to toggle between different product sizes. However, I am facing difficulties in achieving this functionality without having to create separate functions for ea ...

Searching for values using keys in Angular

Currently, I am working on a project using Angular where I need to store information based on specific identifiers. To display this information in the Angular application, I am pulling data for different identifiers and showing it on the screen. At the mo ...

Is it advisable to perform several Firestore queries within a single cloud function to minimize round-trip times?

Exploration Within my application scenario, I have a specific screen that displays 8 different lists of items. Each list requires a separate query to Firestore, running asynchronously to retrieve documents from various collections. Through profiling the e ...

What is the Process of Removing an Element from a List?

I am working with a List of cards known as "_deck": private List<String> _deck = new List<String> {"2h", "3h", "4h", ... } My goal is to remove a card from the start of the List and store it in a variable. I have ...

Ways to maintain the scale of an image while setting specific dimensions for width and height

Is there a way to resize an image to a specific width and height without distorting the scale? In my asp.net c# application, I am using a handler to manipulate images of various sizes. How can I resize an image to a width and height of 300 while maintaini ...

Having trouble getting the Vue.js Element-UI dialog to function properly when embedded within a child component

Take a look at the main component: <template lang="pug"> .wrapper el-button(type="primary", @click="dialogAddUser = true") New User hr // Dialog: Add User add-edit-user(:dialog-visible.sync="dialogAddUser") </template> <s ...

The Angular filter is failing to display the category value

My issue lies in adding a filter to display categories, as my setCurrentCategory function is not showing any value but instead displaying 'undefined'. The goal is to show the category for each person. I'm using ng-click to pass to my functio ...

What is the best way to incorporate vue-chartkick into my components?

I recently integrated the vue-chartkick library with Laravel, following the instructions in the provided documentation. npm install vue-chartkick chart.js In my resources/js/app.js file, I made the necessary modifications: import Chartkick from 'vue- ...

Storing a JSON as a cookie in a Django response

Is there a way to store a dictionary/json object in a client-side cookie from Django and retrieve it as a JavaScript object? response = HttpResponseRedirect(reverse('app:home')) response.set_cookie('cookiekey', 'value') retu ...

The code below is not working as it should be to redirect to the home page after logging in using Angular. Follow these steps to troubleshoot and properly

When looking at this snippet of code: this.router.navigate(['/login'],{queryParams:{returnUrl:state.url}}); An error is displayed stating that "Property 'url' does not exist on type '(name: string, styles: AnimationStyleMetadata". ...

Issue with ThreeJs: Difficulty loading separate images on top and bottom surfaces

I've been trying to place different textures on the top and bottom sides using Threejs to display unique images on each side. However, I'm encountering an issue where the same image is being displayed on both the top and bottom sides. Below is th ...

The behavior of Ajax is resembling that of a GET method, even though its intended method

Greetings, I am currently facing an issue while coding in Javascript and PHP without using jQuery for Ajax. My aim is to upload a file over Ajax and process it in PHP. Here is the code snippet: index.html <html> <head> <title>PHP AJAX ...

What is the process to access array elements in AngularJS?

When coding in HTML, <select class="element-margin-top" ng-model="vm.selectedRole" ng-options="(roleName,enabled) in vm.roleNames"> <option value="">All Roles</option>{{vm.roles[0]}} </select> I am tryin ...

What is the process for updating information in Vue.js?

I need assistance with displaying the updated data in a modal. When I trigger the testing(data) function through a click event, the data appears correctly within the function. However, the template does not update and still shows the previous data. How can ...

The Nextjs application folder does not contain the getStaticPaths method

I encountered a problem with the latest nextjs app router when I tried to utilize SSG pages for my stapi blog, but kept receiving this error during the build process app/blog/[slug]/page.tsx Type error: Page "app/blog/[slug]/page.tsx" does not m ...