53

我正在使用 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;

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

// _e

4

10 回答 10

71

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

打电话

saveAs(file, 'filename');

完整的 http post 请求:

$http.post('apiUrl', myObject, { responseType: 'arraybuffer' })
  .success(function(data) {
            var file = new Blob([data], { type: 'application/pdf' });
            saveAs(file, 'filename.pdf');
        });
于 2014-05-15T16:22:35.113 回答
56

在这里,您有任何客户端都必须执行的对 API 的 angularjs http 请求。只需根据您的情况调整 WS url 和参数(如果有)。这是 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
});

代码说明:

  1. Angularjs 在 URL 处请求一个 file.pdf /path/to/your/API:.
  2. 响应收到成功
  3. 我们在前端使用 JavaScript 执行一个技巧:
    • 创建一个 html 链接 ta: <a>
    • 点击超链接<a>标签,使用JSclick()函数
  4. <a>单击后删除 html标记。
于 2014-12-12T11:41:47.333 回答
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);
     }
});

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

于 2013-01-15T14:56:21.613 回答
8

There is 2 ways to do it in angularjs..

1) By directly redirecting to your service call..

<a href="some/path/to/the/file">clickme</a>

2) By submitting hidden form.

$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();

}

use the hidden element when you have to post some element

<button ng-click="saveAsPDF()">Save As PDF</button>
于 2014-11-10T09:54:11.380 回答
3

tremendows 的解决方案对我来说效果很好。但是,文件也没有保存在 Internet Explorer 10+ 中。以下代码适用于 IE 浏览器。

var file = new Blob(([data]), { type: 'application/pdf' });
if (window.navigator.msSaveOrOpenBlob) {
    navigator.msSaveBlob(file, 'fileName.pdf');
}
于 2015-11-20T03:48:44.773 回答
3

这就是我解决这个问题的方法

$scope.downloadPDF = function () {
    var link = document.createElement("a");
    link.setAttribute("href",  "path_to_pdf_file/pdf_filename.pdf");
    link.setAttribute("download", "download_name.pdf");
    document.body.appendChild(link); // Required for FF
    link.click(); // This will download the data file named "download_name.pdf"
}
于 2016-09-05T13:45:37.120 回答
3

另一个使用Blob()代码的例子:

function save(url, params, fileName){
    $http.get(url, {params: params}).success(function(exporter) {
        var blob = new Blob([exporter], {type: "text/plain;charset=utf-8;"});
        saveAs(blob, fileName);
    }).error(function(err) {
        console.log('err', err);
    });
};

// Save as Code
function saveAs(blob, fileName){
    var url = window.URL.createObjectURL(blob);

    var doc = document.createElement("a");
    doc.href = url;
    doc.download = fileName;
    doc.click();
    window.URL.revokeObjectURL(url);
}
于 2016-06-01T21:49:04.150 回答
0
string trackPathTemp = track.trackPath;

            //The File Path
            var videoFilePath = HttpContext.Current.Server.MapPath("~/" + trackPathTemp);

            var stream = new FileStream(videoFilePath, FileMode.Open, FileAccess.Read);
            var result = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StreamContent(stream)
            };
            result.Content.Headers.ContentType = new MediaTypeHeaderValue("video/mp4");
            result.Content.Headers.ContentRange = new ContentRangeHeaderValue(0, stream.Length);
            // result.Content.Headers.Add("filename", "Video.mp4");
            result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = "Video.mp4"
            };
            return result;
于 2014-04-01T10:39:14.247 回答
0

使用 FileSaver.js 解决了我的问题感谢帮助,下面的代码帮助了我

'$'

 DownloadClaimForm: function (claim) 
{
 url = baseAddress + "DownLoadFile";
 return  $http.post(baseAddress + "DownLoadFile", claim, {responseType: 'arraybuffer' })
                            .success(function (data) {
                                var file = new Blob([data], { type: 'application/pdf' });
                                saveAs(file, 'Claims.pdf');
                            });


    }
于 2016-09-29T09:37:24.677 回答
0

有角服务写的角文件服务器 使用FileSaver.jsBlob.js

 vm.download = function(text) {
    var data = new Blob([text], { type: 'text/plain;charset=utf-8' });
    FileSaver.saveAs(data, 'text.txt');
  };
于 2018-01-16T14:44:57.497 回答