在HTTP下载请求标头中设置接受 [英] Set Accepts in HTTP Download Request Header

查看:87
本文介绍了在HTTP下载请求标头中设置接受的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个返回发票的WCF Web Api端点: http://localhost/api/invoice/23

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

它返回的格式是请求中accepts标头的格式.如果Javascript需要JSON或XML,则只需在accept标头中进行设置.这就是WCF Web Api似乎起作用的方式.我在发票中添加了PDF格式化程序,以便在请求application/pdf时,它将获得具有适当MIME类型的渲染的pdf文件流.效果很好,我可以在提琴手中进行测试.

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.

我需要用户在浏览器中单击某些内容以开始PDF下载并弹出打开/保存"对话框.我不知道如何执行此操作并设置请求的accept标头. javascript中的静态链接或window.location无法正常工作,因为它不允许我设置标题. AJAX请求无法正常运行,因为尽管我可以设置标题,但它希望文本返回,并且不会在浏览器中显示为下载内容.

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.

推荐答案

您可以在JavaScript中动态创建表单,并要求其在新标签页中启动.那应该给你你想要的东西.

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

这篇关于在HTTP下载请求标头中设置接受的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆