Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Accepts in HTTP Download Request Header

I have a WCF Web Api endpoint that returns an invoice: http://localhost/api/invoice/23

The format it returns is that of the accepts header in the request. If the Javascript wants JSON or XML then it just sets this in the accept header. This is how WCF Web Api seems to work. I've added a PDF formatter to invoice so that when asking for application/pdf it will get a rendered pdf file stream back with the appropriate MIME type. This works fine and I can test it in fiddler.

I need the user to click something in the browser to start the PDF download and pop up the open/save dialog. I don't know how to do this and set the accept header of the request. Static links or window.location in javascript won't work because it doesn't let me set the header. AJAX request won't work because although I can set the header, it expects text back and it won't show as a download in the browser.

I'm not sure how I can do this. Any suggestions would be greatly appreciated.

like image 630
Daniel Revell Avatar asked Dec 05 '25 01:12

Daniel Revell


2 Answers

You can just dynamically create a form in JavaScript and ask it to start in a new tab. That should give you what you want.

function SubmitRequest() 
{
        var myForm = document.createElement("form");
        myForm.method = "post";
        myForm.action = "url here"
        var myInput = document.createElement("input");
        myInput.setAttribute("name", "json");
        myForm.setAttribute("target", "_blank");
        myInput.setAttribute("value", "Your value here");
        myForm.appendChild(myInput);
        document.body.appendChild(myForm);
        myForm.submit();
        document.body.removeChild(myForm);
    }
like image 64
Iain Kelwick Avatar answered Dec 07 '25 13:12

Iain Kelwick


The easiest way is to add an A tag in your page with a link to http://localhost/api/invoice/23.pdf and then use the AddUriPathExtensionMapping on your formatter to have it generate the accept header automatically from the path extension on the URI.

like image 31
Darrel Miller Avatar answered Dec 07 '25 14:12

Darrel Miller



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!