【问题标题】:Downloaded files in Angularjs doesn't saves properlyAngularjs 中下载的文件无法正确保存
【发布时间】:2018-01-22 16:16:03
【问题描述】:

我的 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 服务调用请求这个方法时,文件没有打开。图像文件给我以下错误

以下为 PDF

并关注 zip

来自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 方面缺少什么?我尝试了很多代码 sn-ps,但它们都不起作用!

【问题讨论】:

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


    【解决方案1】:

    各位,问题已通过将 $resource 替换为 $http 调用来解决。 这是工作代码,

    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。

    【讨论】:

    • 非常感谢!我花了 2 天时间了解为什么我通过 $resource 下载了损坏的文件。
    猜你喜欢
    • 2012-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多