javascript - Angularjs 中的下载文件无法正确保存

标签 javascript angularjs web-services http asp.net-web-api

我的 Web API 方法返回单个文件或包含多个文件的 zip 文件。这是 Web API 实现。

        public HttpResponseMessage Download([FromUri] List<string> fileNames)
        {
            try
            {
                HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
                if (fileNames.Count > 1)
                {
                    List<string> filePaths = new List<string>();
                    
                    MemoryStream memoryStreamOfFile = new MemoryStream();

                    using (ZipFile zip = new ZipFile())
                    {
                        foreach (var fileName in fileNames)
                        {
                            zip.AddFile(HttpRuntime.AppDomainAppPath + @"\Uploaded\" + fileName);
                        }
                        zip.Save(memoryStreamOfFile);
                        memoryStreamOfFile.Seek(0, SeekOrigin.Begin);
                        result.Content = new StreamContent(memoryStreamOfFile);
                        result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
                        result.Content.Headers.ContentDisposition.FileName = "files.zip";
                        result.Content.Headers.ContentType =
                            new MediaTypeHeaderValue("application/octet-stream");
                        return result;
                    }
                }

                if (!string.IsNullOrEmpty(fileNames[0]))
                {
                    string filePath = HttpRuntime.AppDomainAppPath + @"\Uploaded\" + fileNames[0];
                    
                    var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                    result.Content = new StreamContent(stream);
                    result.Content.Headers.ContentType =
                        new MediaTypeHeaderValue("application/octet-stream");
                    return result;
                }
                return this.Request.CreateResponse(HttpStatusCode.NotFound, "File not found.");
            }
            catch (Exception ex)
            {
                return this.Request.CreateResponse(HttpStatusCode.InternalServerError, ex);
            }
        }

此方法运行良好,我敢肯定,因为当我通过 Google Chrome 扩展“Advanced Rest Client”请求此方法时,文件已下载并运行良好。

但是当我通过 Angularjs 服务调用请求此方法时,文件无法打开。图像文件给我以下错误

enter image description here

以下为 PDF

enter image description here

和下面的 zip

enter image description here

来自 Advance Rest Client行为是预期的,但不是 Angularjs。 以下是我的 Angular 代码

"download": {
        method: "GET",
        url: "api/files/Download/",
        params: { fileNames: "@fileNames" },
        responseType: "arraybuffer",
        headers: {
            'Content-Type': "application/octet-stream"
        }
 }    

return fileManagerClientService.download({ fileNames: fileName })
                .$promise
                .then(function (data) {
                    
                    console.log(data);
                    appInfo.setInfo({ message: "files downloaded successfully" });

                    try {
                        var blob = new Blob([data]);

                        if (typeof (fileName) == "string")
                            FileSaver.saveAs(blob, fileName);
                        else
                            FileSaver.saveAs(blob, "AllFiles.zip");

                    } catch (ex) {
                        console.log(ex);
                    }
                },

请告诉我在 Angular 方面我缺少什么?我已经尝试了很多代码片段,但它们都不起作用!

最佳答案

伙计们,这个问题通过用 $http 调用替换 $resource 来解决。 这是工作代码,

function download(fileName) {
            appInfo.setInfo({ busy: true, message: "loading files" });
            

            return $http({
                method: "GET",
                url: "api/files/Download/",
                params: { fileNames: fileName },
                responseType: "arraybuffer"
            }).then(function (data) {
                appInfo.setInfo({ message: "files downloaded successfully" });

                try {
                    var blob = new Blob([data.data]);

                    if (typeof (fileName) == "string")
                        FileSaver.saveAs(blob, fileName);
                    else
                        FileSaver.saveAs(blob, "AllFiles.zip");

                } catch (ex) {
                    console.log(ex);
                }
            }, function (error) {

            });
        }

这是工作代码,我希望有人使用 $resource 有更好的解决方案,以及为什么它不能与 $resource 一起工作。

关于javascript - Angularjs 中的下载文件无法正确保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45681050/

相关文章:

javascript - API 上的 jQuery 不会自动绑定(bind)

javascript - 在开发过程中自动连续运行 Jasmine 测试

javascript - 如何在 Angular html 中使用自动增量变量

javascript - 如何在 visual studio 项目中查找关键字

java - 添加不带命名空间的 SOAP header 元素

c# - 尝试调用 Web 服务时出现 channel 超时错误

android - 如何使用 ksoap2 将字符串数组传递给 webservice?

javascript - 异步 waterfall/Node.js 未定义 'callback'

javascript - 有 Angular 。 AJAX 请求后启动新的 Angular Directive(指令)

javascript - PageMethods 未定义错误