我在我的页面上点击了一个链接,我正在尝试生成一个PDF文档,然后在浏览器上显示“打开-保存”提示。
我的超文本标记语言(reactjs组件)具有以下代码,其中onclick调用_getMyDocument函数,该函数随后调用Webapi方法。
<div className="row">
<a href="#" onClick={this._getMyDocument.bind(this)}>Test Link</a>
</div>
_getMyDocument(e) {
GetMyDocument(this.props.mydata).then(()=> {
}).catch(error=> {
});我的控制器有以下代码
[HttpPost]
[Route("Generate/Report")]
public IHttpActionResult GetMyReport(MyData myData)
{
byte[] myDoc = MyBusinessObject.GenerateMyReport(myData);
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(myDoc)
};
result.Content.Headers.ContentDisposition =
new ContentDispositionHeaderValue("attachment")
{
FileName = "MyDocument.pdf"
};
result.Content.Headers.ContentType =
new MediaTypeHeaderValue("application/octet-stream");
var response = ResponseMessage(result);
return response;
}目前所有的代码都会执行,但是我没有得到PDF下载提示。我在这里做错了什么?
来自ajax调用锁的成功响应对象,如下所示

发布于 2016-11-24 14:43:10
您来自服务器的响应看起来很好。缺少的部分是您没有以正确的方式处理来自客户端的响应。
让我们假设您的资源url对象在js中如下所示。(也就是说,您已经知道资源url,如果您还不知道,那么您需要单独调用服务器才能知道下载url)
response.downloadUrl = app/media/fileId/document.pdf你所要做的就是设置,
window.location = item.downloadUrl;这将导致浏览器向服务器请求资源,来自服务器的响应必须包含 Content-Disposition:attachment;。它将使浏览器显示下载对话框。
附注:我最近开发了一个类似的功能。如果你有什么问题,请提出来。
当您想要强制浏览器显示某些文件(或资源)的下载提示时,您必须在响应头中包含Content-Disposition:attachment; (您已经这样做了)。
发布于 2016-11-23 19:40:55
一种简单的方法是在您的服务器上使用GET方法,并通过查询参数接收数据。
然后在你的客户端应用程序中,你只需要创建一个经典的链接:
<a href="http://your-server.com/your-resource?param1=123¶m2=456">Test Link</a>或者使用这个简单的js脚本,如果你想从你的脚本逻辑来管理它:
window.open("http://your-server.com/your-resource?param1=123¶m2=456");发布于 2016-11-21 00:26:25
在我们的应用程序(Angular)中,我们必须为它创建一个对象url,代码如下:
WebApi:
result = Request.CreateResponse(HttpStatusCode.OK);
result.Content = new ByteArrayContent(data);
result.Content.Headers.Add("Content-Type", "application/pdf");
result.Content.Headers.ContentDisposition =
new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = "FileNameHere"
};
return result;javascript:
// HttpCall in here
// On SuccessResponse
var file = new Blob([data], {
type: 'application/pdf'
});
var fileURL = URL.createObjectURL(file);
// create an anchor and click on it.
var ancorTag = document.createElement('a');
ancorTag.href = fileURL;ancorTag.target = '_blank';
ancorTag.download = 'CouponOrder.pdf';
document.body.appendChild(ancorTag);
ancorTag.click();
document.body.removeChild(ancorTag);https://stackoverflow.com/questions/40662885
复制相似问题