不使用ajax下载文件

download file without using ajax

本文关键字:下载 文件 ajax      更新时间:2023-09-26

我试图按照这个例子来显示进度条,而不使用ajax来下载文件。

我使用敲除、html和webapi。我有下面的代码,它调用按钮的点击事件href

this.getMeData= function () {
    uRlPath("/api/GetSomeData?id=" + 12)
                + "&name=" + getName.toString()
                + "&downloadtoken=" + new Date().getTime());
    $('#myLink').click();
    location.href = $('#myLink').attr('href');

    };

这是我的html

   <tr>
            <td class="labelText">
                <button data-bind="click: getMeData">
                   Download Data
                </button>
            </td>
        </tr>
        <tr>
            <td>
               <a id="myLink" data-bind="attr: { href: uRlPath }" style="visibility: hidden">Open </a>
            </td>
        </tr>

我现在想在我的href的点击事件上调用一些函数

这是我的webapi方法,它返回cookie和二进制文件

 public HttpResponseMessage GetSomeData(int id, string name, string downloadtoken)
    {
      var returnData= new HttpResponseMessage(HttpStatusCode.OK);
      returnData.Content = new ByteArrayContent(mybyteArray);
       var cookie = new CookieHeaderValue("downloadtoken", downloadtoken);
        returnData.Headers.AddCookies(new CookieHeaderValue[] { cookie });
      returnData.Content.Headers.ContentDisposition =
            new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
        returnData.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");

        returnData.Content.Headers.ContentDisposition.FileName = "myfile.pdf";
        return returnData;
    }

确切地说,我希望有和示例中提供的行为相同的行为。例如,他们使用表单提交,但我没有任何表单,因为我只是使用html,敲除。我已经包括了示例中提到的所有库。

如果你需要更多的投入,请告诉我。

我自己找到了解决方案。我使用以下代码不断检查cookie

var attempts = 30;
var checkTime
        startProgressBar(true)
        checkTime= window.setInterval(function () {
            var cookieValue = $.cookie('downloadtoken');
            if ((cookieValue == token) || (attempts == 0)){
                 stopDownload();
            }
            attempts --;
        }, 1000);

finishDownload功能中,我清除cookie并停止进度条

 function stopDownload() {
        window.clearInterval(checkTime);
        $.cookie('downloadtoken', null); //clears this cookie value
        stopProgressBar(false);
    }

这是进度条的html代码

 <div  data-bind="visible: stopProgressBar" style="top:248px;left: 320px;">
    <img src="../images/ProgressBar.jpg"  />
</div>

如果你只想在点击链接时调用blockUIForDownload函数,你可以通过"点击"绑定来完成,就像你对按钮所做的那样:

<a id="myLink" data-bind="attr: {href: uRlPath}, click: blockUIForDownload" style="visibility: hidden">Open</a>

(这假设函数已经在viewModel中定义。)

请参阅此处的"点击"绑定官方文档:http://knockoutjs.com/documentation/click-binding.html

然而,在我看来,你有点过于复杂了——在你发布的例子中,需要一个隐藏的输入字段,因为他们使用表单输入将令牌传输到服务器。

在您的情况下,令牌是作为href属性的一部分传递的,因此您可以极大地简化代码:

1) 完全删除不可见的链接

2) 将getMeData函数替换为以下内容:

this.getMeData= function () {
    window.open("/api/GetSomeData?id=" + 12
                + "&name=" + getName.toString()
                + "&downloadtoken=" + new Date().getTime());
    blockUIForDownload();
    };