提示文件下载 [英] Prompt file download

查看:126
本文介绍了提示文件下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的页面上有一个链接点击我试图生成PDF文档,然后在浏览器上显示打开 - 保存提示。

I have a link on my page on click of which I am trying to generate a PDF document and then show the "Open - Save" prompt on the browser.

我的HTML(reactjs组件)具有以下代码,其中 onclick 调用 _getMyDocument 函数,然后调用Webapi方法。

My HTML (reactjs component) has the below code where onclick calls the _getMyDocument function which then calls a Webapi method.

 <div className="row">
     <a href="#" onClick={this._getMyDocument.bind(this)}>Test Link</a>
 </div>  

_getMyDocument(e) {
            GetMyDocument(this.props.mydata).then(()=> {
   }).catch(error=> {

  });

我的控制器具有以下代码

My Controller has the below code

[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下载提示。我在这里做错了什么?

Currently all the code executes but I don't get the file PDF download prompt. What am I doing wrong here?

成功的响应对象来自ajax调用lokks如下

Response object on success from the ajax call lokks like below

推荐答案

您对服务器的响应看起来不错。
缺少的部分是你没有以正确的方式从客户端处理这个响应。

Your response from the server looks good. The missing part is that you are not handling this response from the client side in the correct way.

让我们假设你的资源url对象如下所示JS。 (即您已经知道资源网址,如果您还不知道,那么您需要单独调用服务器才能知道下载网址)

Lets assume that your resource url object looks like below in js. (i.e. you already know the resource url, if you don't know it yet, then you will need a separate call to the server to know the download url)

response.downloadUrl = app/media/fileId/document.pdf

您需要做的就是设置,

window.location = item.downloadUrl;

这将导致浏览器从服务器请求资源,来自服务器的响应必须包含 Content-Disposition:attachment; 。它将使浏览器显示下载对话框。

This will cause the browser to request a resource from the server, the response from the server must include Content-Disposition:attachment;. It will cause the browser to show the download dialog.

P.S。我最近研究过类似的功能。如果您有任何疑问,请询问。

P.S. I have recently worked on a similar functionality. If you have questions please ask.

如果要强制浏览器显示某些文件(或资源)的下载提示,则必须包含 Content-Disposition:附件; 在响应标题中(您已经做过)。

When you want to force the browser to show the download prompt for some files (or resources), you must include Content-Disposition:attachment; in the response header (which you already did).

这篇关于提示文件下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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