如何使用AngularJS下载文件并调用MVC API?

Edw*_*ran 52 angularjs

我正在使用AngularJS,我有一个MVC 4 API,它返回带有附件的HttpResponseMessage.

var result = new MemoryStream(pdfStream, 0, pdfStream.Length) {
     Position = 0
};
var response = new HttpResponseMessage {
     StatusCode = HttpStatusCode.OK,
     Content = new StreamContent(result)
};
response.Content.Headers.ContentDisposition = 
           new ContentDispositionHeaderValue("attachment") {
                    FileName = "MyPdf.pdf"
           };
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return response;
Run Code Online (Sandbox Code Playgroud)

我正在使用一个名为fileDownload的jQuery插件...下载文件很漂亮...但我还没有找到以"Angular"方式执行此操作的方法...任何帮助将不胜感激.

// _e

Nao*_*aoe 69

我有同样的问题.通过使用名为FileSaver的javascript库解决了这个问题

打电话吧

saveAs(file, 'filename');
Run Code Online (Sandbox Code Playgroud)

完整的http发布请求:

$http.post('apiUrl', myObject, { responseType: 'arraybuffer' })
  .success(function(data) {
            var file = new Blob([data], { type: 'application/pdf' });
            saveAs(file, 'filename.pdf');
        });
Run Code Online (Sandbox Code Playgroud)

  • 我发现的最佳解决方案.我在研究期间看到了这么多愚蠢的人 (6认同)

tre*_*ows 52

在这里,您可以获得任何客户端必须执行的对angular API的angularjs http请求.只需调整WS url和params(如果有的话)就可以了.这是Naoe的答案和这一个的混合:

$http({
    url: '/path/to/your/API',
    method: 'POST',
    params: {},
    headers: {
        'Content-type': 'application/pdf',
    },
    responseType: 'arraybuffer'
}).success(function (data, status, headers, config) {
    // TODO when WS success
    var file = new Blob([data], {
        type: 'application/csv'
    });
    //trick to download store a file having its URL
    var fileURL = URL.createObjectURL(file);
    var a = document.createElement('a');
    a.href = fileURL;
    a.target = '_blank';
    a.download = 'yourfilename.pdf';
    document.body.appendChild(a); //create the link "a"
    a.click(); //click the link "a"
    document.body.removeChild(a); //remove the link "a"
}).error(function (data, status, headers, config) {
    //TODO when WS error
});
Run Code Online (Sandbox Code Playgroud)

代码说明:

  1. Angularjs在URL处请求file.pdf : /path/to/your/API.
  2. 收到回复的成功
  3. 我们在前端用JavaScript执行一个技巧:
    • 创建一个html链接ta : <a>.
    • <a>使用JS click()函数单击超链接标记
  4. <a>单击后删除html 标记.

  • 要在链接添加到dom后删除链接,只需将成功处理程序中的最后两行替换为:`var element = document.body.appendChild(a); a.click(); document.body.removeChild(element);` (3认同)
  • 根据[MDN](https://developer.mozilla.org/en/docs/Web/API/Blob),IE10是最低要求. (2认同)
  • responseType : 'arraybuffer' 与众不同! (2认同)

Edw*_*ran 10

根据各种帖子...你不能通过XHR触发下载.我需要实现下载条件,因此,我的解决方案是:

//make the call to the api with the ID to validate
someResource.get( { id: someId }, function(data) {
     //confirm that the ID is validated
     if (data.isIdConfirmed) {
         //get the token from the validation and issue another call
         //to trigger the download
         window.open('someapi/print/:someId?token='+ data.token);
     }
});
Run Code Online (Sandbox Code Playgroud)

我希望以某种方式,或有一天可以使用XHR触发下载以避免第二次调用.// _e

  • 为了保持"有角度"的东西,请务必使用$ window或$ location来启动文件下载. (3认同)

小智 8

在angularjs中有两种方法可以做到这一点.

1)直接重定向到您的服务电话..

<a href="some/path/to/the/file">clickme</a>
Run Code Online (Sandbox Code Playgroud)

2)通过提交隐藏的表格.

$scope.saveAsPDF = function() {
    var form = document.createElement("form");
    form.setAttribute("action", "some/path/to/the/file");
    form.setAttribute("method", "get");
    form.setAttribute("target", "_blank");

    var hiddenEle1 = document.createElement("input");
    hiddenEle1.setAttribute("type", "hidden");
    hiddenEle1.setAttribute("name", "some");
    hiddenEle1.setAttribute("value", value);

    form.append(hiddenEle1 );

    form.submit();

}
Run Code Online (Sandbox Code Playgroud)

当你必须发布一些元素时使用隐藏元素

<button ng-click="saveAsPDF()">Save As PDF</button>
Run Code Online (Sandbox Code Playgroud)