AngularJS保存从Web API 2发送的图像文件 [英] AngularJS save image file sent from Web API 2

查看:306
本文介绍了AngularJS保存从Web API 2发送的图像文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试关注下载从我的Web API发送的文件的不同帖子。到目前为止,我可以得到文件来,它将打开下载窗口,它将保存。但是,我不能打开它,所以某些东西在某处是错误的。

I have been trying to follow different posts on downloading a file sent from my Web API. So far I can get the file to come, it will open the download window and it will save. However, I cannot open it so something must be wrong somewhere.

这是我的AngularJS到目前为止。

Here is my AngularJS so far.

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


        });

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

That will make my successfully download the image for me. However, this doesn't let me open the file so either something is still wrong on client side or server side.

服务器端代码:

[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;

    }


推荐答案


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

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图像。

When the responseType is not valid, the XHR API defaults to decoding the response as UTF-8. This corrupts binary files such as JPEG images.

有关更多信息,请参阅 MDN XHR Web API - responseType

For more information, see MDN XHR Web API - responseType.

而不是创建一个< a download>< / a> code>元素与JavaScript DOM操作,考虑使用AngularJS框架。

Instead of creating a <a download></a> element with JavaScript DOM manipulation, consider using the AngularJS framework.

这是一个变得活跃的下载按钮的示例之后从服务器加载数据:

This is an example of a Download button that becomes active after the data is loaded from the server:

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

xdHref 指令

The xdHref Directive

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

PLNKR上的演示

这篇关于AngularJS保存从Web API 2发送的图像文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆