如何使用AngularJS和调用MVCAPI下载文件?

如何使用AngularJS和调用MVCAPI下载文件?,angularjs,Angularjs,我使用的是AngularJS,我有一个MVC4API,它返回带有附件的HttpResponseMessage var result = new MemoryStream(pdfStream, 0, pdfStream.Length) { Position = 0 }; var response = new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = new StreamContent

我使用的是AngularJS,我有一个MVC4API,它返回带有附件的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;
我正在使用一个名为。。。下载的文件很漂亮。。。但是我还没有找到用“角度”的方法来做这件事。。。任何帮助都将不胜感激


//_e

每个不同的帖子。。。您不能通过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触发下载,以避免第二次调用_我也有同样的问题。通过使用名为

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;
就打电话

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');
        });

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

1) 通过直接重定向到您的服务呼叫

<a href="some/path/to/the/file">clickme</a>
当您必须发布某些元素时,请使用隐藏元素

<button ng-click="saveAsPDF()">Save As PDF</button>
另存为PDF

这里有angularjs对API的http请求,任何客户端都必须这样做。只需根据您的情况调整WS-url和参数(如果有)。这是Naoe的答案和:

代码说明:

$http.post('apiUrl', myObject, { responseType: 'arraybuffer' })
  .success(function(data) {
            var file = new Blob([data], { type: 'application/pdf' });
            saveAs(file, 'filename.pdf');
        });
  • Angularjs请求一个文件.pdf,其URL为:
    /path/to/your/API
  • 响应时收到成功消息
  • 我们在前端使用JavaScript执行一个技巧:
    • 创建一个html链接ta:
    • 使用JS
      Click()
      函数单击超链接
      标记
  • 单击后删除html
    标记

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

    var file = new Blob(([data]), { type: 'application/pdf' });
    if (window.navigator.msSaveOrOpenBlob) {
        navigator.msSaveBlob(file, 'fileName.pdf');
    }
    

    另一个使用
    Blob()
    code的示例:

    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);
    }
    

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

    $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"
    }
    

    使用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');
                                });
    
    
        }
    

    有人写了一封信 使用FileSaver.jsBlob.js

     vm.download = function(text) {
        var data = new Blob([text], { type: 'text/plain;charset=utf-8' });
        FileSaver.saveAs(data, 'text.txt');
      };
    

    要保持“角度”,请确保使用$window或$location启动文件下载。我不想打开新窗口并下载,我如何在相同的情况下进行下载window@prash,则不能使用XHR调用触发下载。我的意思是,您可以序列化到base64,并在回调中查看数据。。。但是,浏览器不允许访问文件系统来存储序列化文档。//_关于这个解决方案的浏览器兼容性有什么想法吗?根据IE10,这是最低要求。响应类型:“arraybuffer”起作用!要在链接添加到dom后完成删除,只需将成功处理程序中的最后两行替换为:
    var element=document.body.appendChild(a);a、 单击();document.body.removeChild(元素)@tremendows谢谢你的回复。是的,我使用的是早于6的版本。我真的尝试了我能找到的任何其他方法,但除了解决方法2外,其他方法对我都不起作用。。。谢谢您可以删除
    a
    element我在这上面找到的最佳解决方案。我在研究中看到了这么多愚蠢的东西什么是myObject?@StealthRabbi myObject是您发送到API的POST数据,f.ex。一个以pdf格式呈现的命令。你能正常工作吗?如果是这样的话,为了帮助别人,你能接受一个答案吗?
     vm.download = function(text) {
        var data = new Blob([text], { type: 'text/plain;charset=utf-8' });
        FileSaver.saveAs(data, 'text.txt');
      };