简体   繁体   English

使用AngularJS和$ http.post在MVC应用程序中下载文件

[英]Downloading a file in MVC app using AngularJS and $http.post

Any help is most welcomed and really appreciated. 任何帮助都将受到极大的欢迎和赞赏。

I have an MVC action which retries a file content from a web service. 我有一个MVC操作,该操作从Web服务重试文件内容。 This action is invoked from a Angular service (located in services.js) using $http.post(action, model) , and the action is returning a FileContentResult object, which contains the byte array and the content type. 使用$http.post(action, model)从Angular服务(位于services.js中)调用此操作,该操作返回一个FileContentResult对象,该对象包含字节数组和内容类型。

public ActionResult DownloadResults(DownloadResultsModel downloadResultsModel)
{
downloadResult = ... // Retrieving the file from a web service
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", downloadResult.FileName));
Response.BufferOutput = false;
return new FileContentResult(downloadResult.Contents, downloadResult.ContentType);
}

The issue I'm having is about the browser not performing the default behavior of handing a file (for example, prompting to open it, saving it or cancel). 我遇到的问题是浏览器未执行处理文件的默认行为(例如,提示打开文件,保存文件或取消文件)。 The action is completed successfully with having the content of the file and the file name (injected to the FileContentResult object), but there s no response from the browser. 具有文件内容和文件名(已注入FileContentResult对象)的操作已成功完成,但是浏览器没有响应。

When I'm replacing the post with $window.location.href , and construct the URI myself, I'm hitting the action and after it completes the browser is handling the file as expected. 当我用$window.location.href替换帖子并自己构造URI时,我要执行操作,完成后浏览器将按预期处理文件。

Does anyone can think of any idea how to complete the 'post' as expected? 有人能想到任何想法如何按预期方式完成“发布”吗?

Thanks, 谢谢,

Elad 埃拉德

I am using below code to download the file, given that the file does exist on the server and client is sending server the full path of the file... 我正在使用下面的代码下载文件,因为文件确实存在于服务器上,并且客户端正在向服务器发送文件的完整路径...

as per you requirement change the code to specify path on server itself. 根据您的要求更改代码以指定服务器本身的路径。

    [HttpGet]
    public HttpResponseMessage DownloadFile(string filename)
    {
        filename = filename.Replace("\\\\", "\\").Replace("'", "").Replace("\"", "");
        if (!char.IsLetter(filename[0]))
        {
            filename = filename.Substring(2);
        }

        var fileinfo = new FileInfo(filename);
        if (!fileinfo.Exists)
        {
            throw new FileNotFoundException(fileinfo.Name);
        }

        try
        {
            var excelData = File.ReadAllBytes(filename);
            var result = new HttpResponseMessage(HttpStatusCode.OK);
            var stream = new MemoryStream(excelData);
            result.Content = new StreamContent(stream);
            result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
            result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = fileinfo.Name
            };
            return result;
        }
        catch (Exception ex)
        {
            return Request.CreateResponse(HttpStatusCode.ExpectationFailed, ex);
        }
    }

and then on client side in angular: 然后在客户端以角度:

    var downloadFile = function (filename) {
        var ifr = document.createElement('iframe');
        ifr.style.display = 'none';
        document.body.appendChild(ifr);
        ifr.src = document.location.pathname + "api/GridApi/DownloadFile?filename='" + escape(filename) + "'";
        ifr.onload = function () {
            document.body.removeChild(ifr);
            ifr = null;
        };
    };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM