0

A task: The user, by clicking on the button, should be able to download and save the file. The file is creating on another service. It can be obtained by post-request with body and headers.

I am using wordpress and my plugin. I can call a php function using form or jquery.

//Accept: application/pdf
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); 
$res = curl_exec($ch);

This returns the headers and response body as a string. (My asp .Net 6 external service returns FileStreamResult from method)

I don't know how to implement saving a file on the user's PC. As far as I understand, I have two ways:

  1. Download the file using curl on the server side. Then somehow transfer the ready file to the user for saving. But then there will be an extra load on the backend.
  2. I can create request body and headers on backend. Then execute this post request on the client side.

I am weak in web development... I think the right way is to make a function on the backend that will return a json with the request body and headers.

I can create a separate php page (I think it's redundant) that will call this function. Or I can call this function from javascript or jquery, but I don't know how to initialize post request to save the file.

Maybe someone has already implemented this behavior and can tell me? Thanks.


upd. #1

I found this solution:

var request = new XMLHttpRequest();
request.responseType = "blob";
request.open("POST", url, true);
request.setRequestHeader("Content-Type", "application/json");
request.onload = function() {
    var url = window.URL.createObjectURL(this.response);
    var a = document.createElement("a");
    document.body.appendChild(a);
    a.href = url;
    a.download = this.response.name || "filename"
    a.click();
}
request.send(json);

But it looks like a dirty hack. And it does not work as it should (the file is first downloaded before saving).


upd. #2

I'm willing to change the method from POST to GET, but I still need to pass the ApiKey in the header. I think my issue is discussed here: https://github.com/whatwg/html/issues/7810

So far, I have not found a way that implements both points:

  1. Adding custom headers to the request.
  2. Showing the file save dialog before it is downloaded.
1

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.