Set Accepts in HTTP Download Request Header

风流意气都作罢 提交于 2020-01-01 16:52:13

问题


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.


回答1:


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);
    }



回答2:


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.



来源:https://stackoverflow.com/questions/7346006/set-accepts-in-http-download-request-header

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!