将文件上传到服务器时,它很棒;没有损坏的文件.但是,当我下载文件时(除了纯txt:s,他们woork)
它们的规模越来越大,变得腐败.经过大量的调查,我不知道会出现什么问题.我只是写文件
作为响应和下载blob的流.
欢迎任何想法!

严重依赖此Thread解决方案; Download file from an ASP.NET Web API method using AngularJS

现行守则如下;

的WebAPI:

[Route("GetFile")]
public HttpResponseMessage GetFile()
{
    HttpResponseMessage result = null;
    //Get file object here
    try 
    {
        IEnumerable<string> headerValues = Request.Headers.GetValues("fileID");
        int key = Int32.Parse(headerValues.FirstOrDefault());
        var fetchFile = db.FileRecords.Single(a => a.id == key);

        var localFilePath = fetchFile.path + fetchFile.name;

        if (!System.IO.File.Exists(localFilePath))
        {
            result = Request.CreateResponse(HttpStatusCode.Gone);
        }
        else
        {// serve the file to the client
            //I have used the x-filename header to send the filename. This is a custom header for convenience.
            //You should set the content-type mime header for your response too,so the browser kNows the data format.
            var info = System.IO.File.GetAttributes(localFilePath);
            result = Request.CreateResponse(HttpStatusCode.OK);
            result.Content = new StreamContent(new FileStream(localFilePath,FileMode.Open,FileAccess.Read));
            result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
            result.Content.Headers.Add("x-filename",fetchFile.name);
            result.Content.Headers.Contentdisposition = new System.Net.Http.Headers.ContentdispositionHeaderValue("attachment");
            result.Content.Headers.Contentdisposition.FileName = fetchFile.name;
        }
        return result;
    }
    catch (Exception e)
    {
        return Request.CreateResponse(HttpStatusCode.BadRequest);
    }
}

视图:

<button type="button" class="btn btn-default btn-sm" data-localize="DOWNLOAD" ng-click="downloadFiles(file)">
    Download file
</button>

控制器:

/******** FILE DOWNLOAD  **********/
$scope.downloadFiles = function (file) {
        $http({
            method: 'GET',cache: false,url: host + 'api/Files/GetFile',headers: {
                'Content-Type': 'application/json; charset=utf-8','fileID': file.id
            }
        }).success(function (data,status,headers) {
            var octetStreamMime = 'application/octet-stream';
            var success = false;

            // Get the headers
            headers = headers();

            // Get the filename from the x-filename header or default to "download.bin"
            var filename = headers['x-filename'] || 'download.bin';

            // Determine the content type from the header or default to "application/octet-stream"
            var contentType = headers['content-type'] || octetStreamMime;

            try {

                console.log(filename);
                // Try using msSaveBlob if supported
                console.log("Trying saveBlob method ...");
                var blob = new Blob([data],{ type: contentType });
                if (navigator.msSaveBlob)
                    navigator.msSaveBlob(blob,filename);
                else {
                    // Try using other saveBlob implementations,if available
                    var saveBlob = navigator.webkitSaveBlob || navigator.mozSaveBlob || navigator.saveBlob;
                    if (saveBlob === undefined) throw "Not supported";
                    saveBlob(blob,filename);
                }
                console.log("saveBlob succeeded");
                success = true;
            } catch (ex) {
                console.log("saveBlob method Failed with the following exception:");
                console.log(ex);
            }

            if (!success) {
                // Get the blob url creator
                var urlCreator = window.URL || window.webkitURL || window.mozURL || window.msURL;
                if (urlCreator) {
                    // Try to use a download link
                    var link = document.createElement('a');
                    if ('download' in link) {
                        // Try to simulate a click
                        try {
                            // Prepare a blob URL
                            console.log("Trying download link method with simulated click ...");
                            var blob = new Blob([data],{ type: contentType });
                            var url = urlCreator.createObjectURL(blob);
                            link.setAttribute('href',url);

                            // Set the download attribute (Supported in Chrome 14+ / Firefox 20+)
                            link.setAttribute("download",filename);

                            // Simulate clicking the download link
                            var event = document.createEvent('MouseEvents');
                            event.initMouseEvent('click',true,window,1,false,null);
                            link.dispatchEvent(event);
                            console.log("Download link method with simulated click succeeded");
                            success = true;

                        } catch (ex) {
                            console.log("Download link method with simulated click Failed with the following exception:");
                            console.log(ex);
                        }
                    }

                    if (!success) {
                        // Fallback to window.location method
                        try {
                            // Prepare a blob URL
                            // Use application/octet-stream when using window.location to force download
                            console.log("Trying download link method with window.location ...");
                            var blob = new Blob([data],{ type: octetStreamMime });
                            var url = urlCreator.createObjectURL(blob);
                            window.location = url;
                            console.log("Download link method with window.location succeeded");
                            success = true;
                        } catch (ex) {
                            console.log("Download link method with window.location Failed with the following exception:");
                            console.log(ex);
                        }
                    }

                }
            }

            if (!success) {
                // Fallback to window.open method
                console.log("No methods worked for saving the arraybuffer,using last resort window.open");
                window.open(httpPath,'_blank','');
            }
            /******************/


        }).error(function (data,status) {

            console.log("Request Failed with status: " + status);

            // Optionally write the error out to scope
            //$scope.errorDetails = "Request Failed with status: " + status;
        });
}
添加了arraybuffer作为GET请求的响应类型,现在浏览器正确解释文件.
/******** FILE DOWNLOAD  **********/
$scope.downloadFiles = function (file) {
        $http({
            method: 'GET',responseType:'arraybuffer','fileID': file.id
            }

尝试使用angularJS和c#webapi从服务器下载文件的更多相关文章

  1. 浅析HTML5中的download属性使用

    这篇文章主要介绍了浅析HTML5中的download属性使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

  2. HTML5 Blob 实现文件下载功能的示例代码

    这篇文章主要介绍了HTML5 Blob 实现文件下载功能的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

  3. web字体加载方案优化小结

    这篇文章主要介绍了web字体加载方案优化小结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

  4. Swift - SQLite中Data类型数据的插入、读取BLOB类型字段

    本文演示如何实现Data类型的数据存取。1,实现原理首先我们建表的时候,用于保存Data数据的字段要使用大数据类型,比如:BLOB读取操作同其他数据类型的读取没什么差别。不过插入的时候要注意,不能直接将数据拼接到sql语句中,而是要使用预处理语句:12letsql="insertintot_imagevalues(?表字段很简单,就一个ID主键,和一个BLOB类型的字段点击“保存”按钮,将项目中的0.png这张图片存储到图片表中。Data//将Data数据插入到数据库"insertintot_imagev

  5. Android Studio是否支持用于Android UI设计的AngularJS?

    我对AndroidStudio有疑问:AS在设计XML文件时是否支持AngularJS代码,例如:对于小动画或效果?

  6. android – 如何使用ClientID和ClientSecret在Phonegap中使用Angularjs登录Google OAuth2

    我正尝试使用Angularjs(使用IonicFramework)通过GoogleOAuth2从我的Phonegap应用程序登录.目前我正在使用http://phonegap-tips.com/articles/google-api-oauth-with-phonegaps-inappbrowser.html进行登录.但是当我使用Angular-UI-RouterforIonic时,它正在创建非常

  7. MvvmCross:从android中的MvxListView获取所选项目的最佳方法是什么?

    我正在使用MvvmCrossv3.06,我在android中定义了一个绑定到列表的MvxListView.我可以看到列表,但无法确定获取单击它时所选项目的最佳方法.目前我在活动的OnCreate中执行以下操作,但它不是特别是MVVM,我想知道是否有更好的方法通过绑定?

  8. 利用require.js与angular搭建spa应用的方法实例

    这篇文章主要给大家介绍了关于利用require.js与angular搭建spa应用的方法实例,文中通过示例代码给大家介绍的非常详细,对大家的理解和学习具有一定的参考学习价值,需要的朋友们下面跟着小编来一起看看吧。

  9. 详解Angular动态组件

    本文主要介绍了Angular动态组件,对此感兴趣的同学,可以亲自实验一下。

  10. 详解如何使用webpack+es6开发angular1.x

    本篇文章主要介绍了详解如何使用webpack+es6开发angular1.x,具有一定的参考价值,有兴趣的可以了解一下

随机推荐

  1. Angular2 innerHtml删除样式

    我正在使用innerHtml并在我的cms中设置html,响应似乎没问题,如果我这样打印:{{poi.content}}它给了我正确的内容:``但是当我使用[innerHtml]=“poi.content”时,它会给我这个html:当我使用[innerHtml]时,有谁知道为什么它会剥离我的样式Angular2清理动态添加的HTML,样式,……

  2. 为Angular根组件/模块指定@Input()参数

    我有3个根组件,由根AppModule引导.你如何为其中一个组件指定@input()参数?也不由AppModalComponent获取:它是未定义的.据我所知,你不能将@input()传递给bootstraped组件.但您可以使用其他方法来做到这一点–将值作为属性传递.index.html:app.component.ts:

  3. angular-ui-bootstrap – 如何为angular ui-bootstrap tabs指令指定href参数

    我正在使用角度ui-bootstrap库,但我不知道如何为每个选项卡指定自定义href.在角度ui-bootstrap文档中,指定了一个可选参数select(),但我不知道如何使用它来自定义每个选项卡的链接另一种重新定义问题的方法是如何使用带有角度ui-bootstrap选项卡的路由我希望现在还不算太晚,但我今天遇到了同样的问题.你可以通过以下方式实现:1)在控制器中定义选项卡href:2)声明一个函数来改变控制器中的散列:3)使用以下标记:我不确定这是否是最好的方法,我很乐意听取别人的意见.

  4. 离子框架 – 标签内部的ng-click不起作用

    >为什么标签标签内的按钮不起作用?>但是标签外的按钮(登陆)工作正常,为什么?>请帮我解决这个问题.我需要在点击时做出回复按钮workingdemo解决方案就是不要为物品使用标签.而只是使用divHTML

  5. Angular 2:将值传递给路由数据解析

    我正在尝试编写一个DataResolver服务,允许Angular2路由器在初始化组件之前预加载数据.解析器需要调用不同的API端点来获取适合于正在加载的路由的数据.我正在构建一个通用解析器,而不是为我的许多组件中的每个组件设置一个解析器.因此,我想在路由定义中传递指向正确端点的自定义输入.例如,考虑以下路线:app.routes.ts在第一个实例中,解析器需要调用/path/to/resourc

  6. angularjs – 解释ngModel管道,解析器,格式化程序,viewChangeListeners和$watchers的顺序

    换句话说:如果在模型更新之前触发了“ng-change”,我可以理解,但是我很难理解在更新模型之后以及在完成填充更改之前触发函数绑定属性.如果您读到这里:祝贺并感谢您的耐心等待!

  7. 角度5模板形式检测形式有效性状态的变化

    为了拥有一个可以监听其包含的表单的有效性状态的变化的组件并执行某些组件的方法,是reactiveforms的方法吗?

  8. Angular 2 CSV文件下载

    我在springboot应用程序中有我的后端,从那里我返回一个.csv文件WheniamhittingtheURLinbrowsercsvfileisgettingdownloaded.现在我试图从我的角度2应用程序中点击此URL,代码是这样的:零件:服务:我正在下载文件,但它像ActuallyitshouldbeBook.csv请指导我缺少的东西.有一种解决方法,但您需要创建一个页面上的元

  9. angularjs – Angular UI-Grid:过滤后如何获取总项数

    提前致谢:)你应该避免使用jQuery并与API进行交互.首先需要在网格创建事件中保存对API的引用.您应该已经知道总行数.您可以使用以下命令获取可见/已过滤行数:要么您可以使用以下命令获取所选行的数量:

  10. angularjs – 迁移gulp进程以包含typescript

    或者我应该使用tsc作为我的主要构建工具,让它解决依赖关系,创建映射文件并制作捆绑包?

返回
顶部