AngularJS 保存从 Web 发送的图像文件 API 2

AngularJS save image file sent from Web API 2

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

这是我的 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;

    }

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

代码:

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:
         
         */
        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();
    }
}

The provided value 'arrayBuffer' is not a valid enum value of type 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 操作创建 <a download></a> 元素,不如考虑使用 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.

 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

最简单的方法对我有用