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

Personalized ES6 Bootstrap module created for a toggle switch button in Vue

Utilizing the custom switch toggle in a Vue application is my current task. Check out this link for more on the custom switch toggle I found a button that suits my needs, but I am unsure how to properly integrate it into my component so it can handle the ...

Conceal the Submit button upon completing the form submission using the load method

When creating a form and sending a request to another page, I use the following code: $(document).ready(function() { $("#send").click(function() { var text = $("#text").val(); var email = $("#email").val(); $("#exp").load("sendmail.php",{text: ...

Implementing optimistic updates with React-query mutations

Hello everyone! I'm a newcomer to react-query and I've been experimenting with making an optimistic update using the mutation function. However, I've encountered a problem where I'm unable to retrieve the previous value from the query. ...

Implement a mouseenter event to all input elements that have specific names stored in an array, utilizing jQuery

I'm struggling to figure out how to apply my function to all input elements with a name that is included in my array. This is what I've attempted so far: var names = ["name1", "name2"]; $(document).ready(function(){ $('input[name=names[ ...

The remaining visible portion of a viewport is equivalent to the height of an element

Is there a way to dynamically set a div's height so that it expands from its starting position to the end of its parent div, which is 100% of the viewport minus 20 pixels? Here is an example of how you can achieve this using jQuery: $(document).read ...

Browser and contexmenu intersecting halfway

I have successfully implemented a custom context menu in my HTML project. It functions well, but I am facing an issue where half of the menu appears off-screen to the right. Is there a way to detect this and reposition the menu above the mouse pointer? He ...

jQuery Refuses to Perform Animation

I'm facing an issue with animating a specific element using jQuery while scrolling down the page. My goal is to change the background color of the element from transparent to black, but so far, my attempts have been unsuccessful. Can someone please pr ...

no output upon completion of a class constructor - JavaScript

I am facing a perplexing issue with my code. Let me break it down for you: class Block{ constructor(timeStamp, lastBlockHash, thisBlockData, thisBlockHash){ this.timeStamp = timeStamp; this.lastBlockHash = lastBlockHash; this.t ...

Error occurred during the authentication process while attempting to upload a file to Firebase storage

While attempting to upload a small file to Firebase storage using Vue.js, I keep encountering a QUOTA_EXCEEDED error. It seems there are an unusually high number of calls to https://securetoken.googleapis.com/v1/token?key=<SomeLongString>. Despite th ...

The functioning of JavaScript's ajax capabilities

Need some help with a coding issue I'm facing. Can anyone provide suggestions for improving my code? I've come across a situation where the table is not updating when using a certain piece of code. However, upon further inspection, I found that ...

Enhanced MUI TextField component with active cursor and focused state

When using the MUI TextField component as a single input form, I encountered an issue where the component loads with focus but no visible cursor to begin typing. To start typing, the user must click into the input field or press the tab key, which then act ...

Load images sequentially in a slideshow gallery using JQuery, showing the next five pictures at a time instead of loading all at once

Recently, I've been developing a slideshow for educational materials and images. However, a concern was raised by a colleague regarding the loading time of slideshows with over 50 images. Is there a way to optimize the loading process by only displayi ...

I'm having trouble getting my home.js to render in the outlet component

After using Material-UI to create navbar.js, I encountered an issue where the other component was not rendering in the <Outlet/> Component RootLayout.js import { Outlet } from "react-router-dom"; import NavBar from "../component/NavBa ...

Express.js app does not seem to properly handle app.use(express.raw()) functionality

I am in the process of creating an Express application that is designed to handle binary post data. The code snippet below showcases my progress so far: Server-side: var express = require('express'); var app = express(); var PORT = 3000; app.us ...

When the App is opened, Firestore triggers a function to run, and then again after any changes

I am looking to activate this function when the App is launched, and then whenever there is an update in my firestore data. export const getDuettsPlayer1 = (setDuetts) => { duettsRef.where("player1", "==", firebase.auth().currentUs ...

"Creating an asset-manifest.json file for Vuejs that mimics React's format: A step-by-step guide

After creating a new app using Vue CLI with PWA enabled, I realized that it does not generate an asset-manifest.json file like Create React App does. The structure of the asset-manifest.json file created by CRA looks like this: To achieve a similar result ...

Avoiding redirection in Django template form

Currently, I am facing a challenge with my application that involves rendering a Django Template model form where images are referenced from another model. To manage the addition and deletion of images for this other model, I have implemented a button wit ...

Transferring data only once specific agreements have been fulfilled

Imagine having a file with specific promises that, when executed sequentially, create an input file called input.txt. // prepareInput.js var step1 = function() { var promise = new Promise(function(resolve, reject) { ... }); return p ...

Send a parameter to an Angular directive when clicked

I am working on a directive that will allow me to retrieve parameters upon clicking. I need to access the child data within the click event to determine if it has children or not. ..... html div ng-app="treeApp"> <ul> <treeparent>< ...

Transforming ajax code into node.js

After mastering ajax calls for client-server interaction, I am facing a challenge in converting my code to a server-side node compatible JS using http requests. Despite reading various tutorials, I am struggling to adapt them to fit with my current code st ...