提示文件下载
我在我的页面上有一个链接点击我试图生成PDF文档,然后在浏览器上显示“打开 – 保存”提示。
我的HTML(reactjs组件)具有以下代码,其中onclick
调用_getMyDocument
函数,然后调用Webapi方法。
_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调用lokks如下
您对服务器的响应看起来不错。 缺少的部分是您没有以正确的方式处理来自客户端的此响应。
让我们假设你的资源url对象在js中如下所示。 (即你已经知道了资源url,如果你还不知道,那么你需要单独调用服务器才能知道下载url)
response.downloadUrl = app/media/fileId/document.pdf
你需要做的就是设置,
window.location = item.downloadUrl;
这将导致浏览器从服务器请求资源,来自服务器的响应必须包括Content-Disposition:attachment;
。 它将使浏览器显示下载对话框。
PS我最近研究过类似的function。 如果您有任何疑问,请询问。
如果要强制浏览器显示某个文件(资源)的下载提示,则必须包含Content-Disposition:attachment;
在响应中(你已经做过)。
一种简单的方法是在服务器上使用GET方法,并通过查询参数接收数据。
然后在您的客户端应用程序中,您只需创建一个经典链接:
Test Link
如果您想从脚本逻辑中管理它,请使用该简单的js脚本:
window.open("http://your-server.com/your-resource?param1=123¶m2=456");
您的问题是GetMyDocument函数将接收PDF文件作为服务器响应,目前您对该响应没有任何作用。 您需要在当时的回调中处理响应。 从javascript保存文件并不是很简单,所以我建议使用filesaver.js等外部库来帮助你。
它最终会看起来像……
_getMyDocument(e) { GetMyDocument(this.props.mydata) .then((response)=> { const returnedFile = new Blob([response], { type: 'application/pdf'}); saveAs(returnedFile); }).catch(error=> { });
在我们的应用程序(角度)中,我们必须使用以下代码创建一个对象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);
创建内容处置并将其添加到响应标头中
var cd = new System.Net.Mime.ContentDisposition { // for example foo.bak FileName = System.IO.Path.GetFileName(fileName), // always prompt the user for downloading, set to true if you want // the browser to try to show the file inline Inline = false, }; Response.AppendHeader("Content-Disposition", cd.ToString());