Craig
Craig

Reputation: 18704

Creating a 'Save As' button for a file generated on the server

On our UI, we allow a user to complete some details, and then we need them to generate a PDF file based on the details entered. So, I make a WebAPI call to the server, posting some details, which in turn generates the binary file.

We would prefer not to save the binary file, but instead, produce a 'Download Now' button, which downloads the PDF when it's ready.

I was hoping to generate the file, and return the result to a state variable.

this.setState({ myFile: result });

Where result is what I get back from the API.

And then when 'result != null', enable a Download button. When the user clicks that button, the this.state.myFile will download ... with a name that I provide (via code).

I'm not sure if saving binary data in state is even possible.

Is there a way to have a button that triggers a download from a state variable? Last resort would be to generate and store the file on the server, and then provide a link - but if we can store it in state and allow the user to click a 'Download' button once the file is in state (They're small - approx between 100k and 300k).

Upvotes: 2

Views: 189

Answers (1)

Jeswin Rebil
Jeswin Rebil

Reputation: 460

You can use something like below

var file = window.URL.createObjectURL(result);
var a = document.createElement("a");
a.href = file;
a.download = "Name of PDF";
document.body.appendChild(a);
a.click();

Upvotes: 2

Related Questions