c# - ASP NET MVC 4 : How to return a file from a controller to view with angularJs?

标签 c# angularjs asp.net-mvc asp.net-mvc-4

我想从服务器下载一个文件,但我不明白我做错了什么。我一直在寻找如何去做,但没有用。这是我找到的一个例子:

Controller (ASP NET MVC):

public HttpResponseMessage GetFile(string filename)
        {
            try
            {
                if (!string.IsNullOrEmpty(filename))
                {
                    //string filePath = HttpContext.Current.Server.MapPath("~/App_Data/") + fileName;
                    DirectoryInfo dirInfo = new DirectoryInfo(HostingEnvironment.MapPath("~/Documentos"));
                    string filePath = dirInfo.FullName + @"\" + filename;

                    using (MemoryStream ms = new MemoryStream())
                    {
                        using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                        {
                            byte[] bytes = new byte[file.Length];
                            file.Read(bytes, 0, (int)file.Length);
                            ms.Write(bytes, 0, (int)file.Length);

                            HttpResponseMessage httpResponseMessage = new HttpResponseMessage();
                            httpResponseMessage.Content = new ByteArrayContent(bytes.ToArray());
                            httpResponseMessage.Content.Headers.Add("x-filename", filename);
                            httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");//application/octet-stream
                            httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
                            httpResponseMessage.Content.Headers.ContentDisposition.FileName = file.Name;
                            httpResponseMessage.StatusCode = HttpStatusCode.OK;
                            return httpResponseMessage;
                        }
                    }
                }
                return new HttpResponseMessage(HttpStatusCode.NotFound);
            }
            catch (Exception)
            {
                return new HttpResponseMessage(HttpStatusCode.BadRequest);
            }
        }

Angular Controller :

    $scope.downloadFiles = function () {
        var filename = "aae49c8e-c523-4ccc-a7ba-88f405072047&file.pdf";           
        $http({
              method: 'GET',
              url: 'serv/Consultas/GetFile',
              params: { filename: filename },
              responseType: "arraybuffer"
      }).success(function (response) {
            var file = new Blob([(response)], { type: 'application/pdf' });
            var fileURL = URL.createObjectURL(file);
            $window.open(fileURL);                    
      }).error(function (data, status) {
         console.log("Request failed with status: " + status);
      });
   }

当我加载文件时,我只得到不完整的文件名“aae49c8e-c523-4ccc-a7ba-88f405072047”并且不加载文件。感谢您的帮助。

最佳答案

从服务器流式传输文件:

public FileStreamResult GetFile(string filename)
{
    try
    {
        if (!string.IsNullOrEmpty(filename))
        {
            //string filePath = HttpContext.Current.Server.MapPath("~/App_Data/") + fileName;
            DirectoryInfo dirInfo = new DirectoryInfo(HostingEnvironment.MapPath("~/Documentos"));
            string filePath = dirInfo.FullName + @"\" + filename;

            FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            return File(fs, "application/pdf");
        }
        return new HttpResponseMessage(HttpStatusCode.NotFound);
    }
    catch (Exception)
    {
        return new HttpResponseMessage(HttpStatusCode.BadRequest);
    }
}

使用 URL 到操作方法打开新窗口,该方法将流式传输 PDF,以便它可以在浏览器中显示:

var fileURL = 'serv/Consultas/GetFile?filename=file.pdf';
$window.open(fileURL);

关于c# - ASP NET MVC 4 : How to return a file from a controller to view with angularJs?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39665171/

相关文章:

c# - 获取堆栈跟踪中的参数值

c# - 上传 ashx 文件 Context.Session 为空

c# - 关于静态构造函数、方法和字段的一些问题

angularjs - 我应该在 AngularJS 中测试什么?

angularjs - POST 方法自动转换为 OPTIONS

c# - 在 Mvc 3 razor View 中,基于模型中的空值有条件地呈现 html 的最佳方法是什么

c# - 链接 Task.Factory.FromAsync 和 ContinueWith 与等待

javascript - Angular.js - 用户界面路由器 |如何确保 $stateParams.anyParam 的值为整数?

jquery - Javascript 和 MVC 返回类型

jquery - ASP.net MVC 验证在不正确的字段上突出显示和图标 Jquery