【问题标题】:AngularJS save image file sent from Web API 2AngularJS 保存从 Web API 2 发送的图像文件
【发布时间】:2017-07-19 22:44:25
【问题描述】:

我一直在尝试关注有关下载从我的 Web API 发送的文件的不同帖子。到目前为止,我可以获取文件,它将打开下载窗口并保存。但是,我无法打开它,所以某处一定有问题。

到目前为止,这是我的 AngularJS。

return $http({
            url: State.Endpoint + "/api/account/picture",
            method: "GET",
            responseType: 'arrayBuffer'
        }).then(function (data) {

            var octetStreamMime = 'application/octet-stream';
            var success = false;

            var file = new Blob([data.data], {
                type: "image/jpeg"
            });


            var fileUrl = URL.createObjectURL(file);

            var a = document.createElement('a');

            a.href = fileUrl;

            a.target = "_blank";

            a.download = "myFile.jpg";

            document.body.appendChild(a);

            a.click();


        });

这将使我为我成功下载图像。但是,这不允许我打开文件,因此客户端或服务器端仍然有问题。

服务器端代码:

[Route("picture")]
    [HttpGet]
    public HttpResponseMessage GetPictureBlob()
    {
        HttpResponseMessage response = null;


        var localFilePath = HttpContext.Current.Server.MapPath("~/Content/Images/demo.jpg");

        if (!File.Exists(localFilePath))
        {
            response = Request.CreateResponse(HttpStatusCode.Gone);
        }
        else
        {

            var fStream = new FileStream(localFilePath, FileMode.Open, FileAccess.Read);
            // Serve the file to the client
            response = new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.OK,
                Content = new StreamContent(fStream)
            };
            response.Content.Headers.ContentDisposition =
            new ContentDispositionHeaderValue("attachment")
            {
                FileName = Path.GetFileName(fStream.Name)
            };
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

            //response.Headers.Add("content-type", "application/octet-stream");

        }

        return response;

    }

【问题讨论】:

  • this doesn't let me open the file 是什么意思?
  • 当我使用画图、​​Photoshop 等任何工具打开文件时,它都不会显示图像。
  • 你提到下载文件,你的意思是显示图像,因为这就是你的代码正在做的事情......如果你想将图像下载到浏览器,那么我会使用插件对于称为 FileSaver 的文件,您可以简单地将该文件保存在客户端。干杯!
  • 是的,我的目标是为客户提供他们要保存到本地计算机的文件。

标签: angularjs download asp.net-web-api2 angularjs-http


【解决方案1】:

 var a = document.createElement("a"); //Create <a>
    a.href = "data:image/png;base64," + ImageBase64;
    a.download = "Image.png"; //File name Here
    a.click(); //Downloaded file

对我来说最简单的方法

【讨论】:

    【解决方案2】:

    提供的值“arrayBuffer”不是 XMLHttpRequestResponseType 类型的有效枚举值。

    使用arraybuffer全部小写:

        $http({
            url: State.Endpoint + "/api/account/picture",
            method: "GET",
            //responseType: 'arrayBuffer'
            //USE arraybuffer lowercase
            responseType: 'arraybuffer'
            //OR
            //responseType: 'blob'
        })
    

    当 responseType 无效时,XHR API 默认将响应解码为 UTF-8。这会损坏二进制文件,例如 JPEG 图像。

    有关详细信息,请参阅MDN XHR Web API - responseType


    创建一个下载按钮

    不要使用 JavaScript DOM 操作创建 &lt;a download&gt;&lt;/a&gt; 元素,而是考虑使用 AngularJS 框架。

    这是一个下载按钮的示例,该按钮在从服务器加载数据后变为活动状态:

    <a download="data_{{files[0].name}}" xd-href="data">
      <button ng-disabled="!data">Download</button>
    </a>
    

    xdHref指令

    app.module("myApp").directive("xdHref", function() {
      return function linkFn (scope, elem, attrs) {
         scope.$watch(attrs.xdHref, function(newVal) {
           if (newVal) {
             elem.attr("href", newVal);
           }
         });
      };
    });
    

    DEMO on PLNKR.

    【讨论】:

    • 技术上第一部分回答了我的问题。不过,我真的很喜欢这里的次要答案。
    • 第二部分是为了方便读者搜索“angularjs save image file sent from web”。其他读者可能想要一个 Angular 解决方案。
    【解决方案3】:

    我对这段代码做了同样的事情,其中​​:

    代码:

    function downloadBlobFile(data, format, name) {
        // format must be one of https://developer.mozilla.org/en-US/docs/Web/API/Blob/type
        var file = new Blob([data], {type: 'application/' + format});
        file.lastModified = new Date();
        file.name = name + '.' + format.trim().toLowerCase();
    
        // guarantee IE compatibility
        if($window.navigator && $window.navigator.msSaveOrOpenBlob) {
            $window.navigator.msSaveOrOpenBlob(file, file.name);
        }
        //other web browser
        else {
            /**
             * Because this technology's specification has not stabilized, compatibility has been
             * checked here: https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL#Browser_compatibility
             */
            var fileURL = $window.URL.createObjectURL(file);
    
            /* trick for downloading the file, borrowed from:
             http://stackoverflow.com/questions/19327749/javascript-blob-filename-without-link
             */
            var a = angular.element("<a style='display: none;'/>").attr("href", fileURL).attr("download", file.name);
            angular.element(document.body).append(a);
            a[0].click();
            $window.URL.revokeObjectURL(fileURL);
            a.remove();
        }
    }
    

    【讨论】:

    • 这看起来是个不错的选择,我需要去另一堂课,但我回来后要测试一下。
    • An observation here:当我在一个项目中使用它和 jQuery 时,你会发现一些代码,例如 $("&lt;a style='display: none;'/&gt;")例如,如果您不使用 jQuery.,您可能想要替换为 document.getElementById('#myElementID')
    • 好的,我刚刚更新了答案,以避免我之前评论过的问题。
    猜你喜欢
    • 1970-01-01
    • 2019-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-16
    相关资源
    最近更新 更多