Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/29.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用angularJS和asp.net mvc下载文件_C#_Asp.net_Angularjs_Asp.net Mvc_Asp.net Mvc 4 - Fatal编程技术网

C# 使用angularJS和asp.net mvc下载文件

C# 使用angularJS和asp.net mvc下载文件,c#,asp.net,angularjs,asp.net-mvc,asp.net-mvc-4,C#,Asp.net,Angularjs,Asp.net Mvc,Asp.net Mvc 4,我是使用asp.NETMVC进行开发的初学者。我正在尝试下载文件(图片,pdf…),这是我的代码 在asp控制器中 [HttpPost] public HttpResponseMessage Download(int id) { var db = new TutorialGEDEntities(); Tutorial fileToDownload = db.Tutorials.Find(id); string name =

我是使用asp.NETMVC进行开发的初学者。我正在尝试下载文件(图片,pdf…),这是我的代码

在asp控制器中

    [HttpPost]
    public HttpResponseMessage Download(int id)
    {
        var db = new TutorialGEDEntities();

        Tutorial fileToDownload = db.Tutorials.Find(id);
        string name = fileToDownload.filepath;
        Debug.WriteLine("filepath  " + name);
        try
        {

            if (!string.IsNullOrEmpty(name))
            {
                //var root = System.Web.HttpContext.Current.Server.MapPath(name);
                var filePath = System.Web.HttpContext.Current.Server.MapPath(name); ;
                char[] s = new char[name.Length - name.LastIndexOf("\\") - 1];
                name.CopyTo(name.LastIndexOf("\\")+1, s, 0, name.Length - name.LastIndexOf("\\")-1);
                String fileName = new String(s);
                using (MemoryStream ms = new MemoryStream())
                {
                    using (FileStream file = new FileStream(name, FileMode.Open, FileAccess.Read))
                    {
                        Debug.WriteLine("file  " + file.Length);
                        byte[] bytes = new byte[file.Length];
                        file.Read(bytes, 0, (int)file.Length);
                        ms.Write(bytes, 0, (int)file.Length);

                        HttpResponseMessage httpResponseMessage = new HttpResponseMessage();
                        ByteArrayContent content = new ByteArrayContent(bytes.ToArray());
                        httpResponseMessage.Content = content;
                        httpResponseMessage.Content.Headers.Add("x-filename", fileName);
                        httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                        httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
                        httpResponseMessage.Content.Headers.ContentDisposition.FileName = fileName;
                        httpResponseMessage.StatusCode = HttpStatusCode.OK;
                        return httpResponseMessage;
                    }
                }
            }
            return null;
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.Data);
            return null;
        }
    }
                $http({
                    method: 'POST',
                    url: 'Download',
                    data: { 'name': file.filepath },
                    responseType: 'arraybuffer'
                }).success(function (content, status, headers) {
                    headers = headers();
                    console.log(content);
                    console.log(status)
                    var filename = headers['x-filename'];
                    var contentType = headers['content-type'];

                    var linkElement = document.createElement('a');
                    try {
                        var blob = new Blob([content], { type: contentType });
                        console.log(blob);
                        var url = URL.createObjectURL(blob);
                        console.log(url)
                        linkElement.setAttribute('href', url);
                        linkElement.setAttribute("download", filename);

                        var clickEvent = new MouseEvent("click", {
                            "view": window,
                            "bubbles": true,
                            "cancelable": false
                        });
                        linkElement.dispatchEvent(clickEvent);
                    } catch (ex) {
                        console.log(ex);
                    }
                }).error(function (data) {
                    console.log(data);
                });
            };
在角度控制器中

    [HttpPost]
    public HttpResponseMessage Download(int id)
    {
        var db = new TutorialGEDEntities();

        Tutorial fileToDownload = db.Tutorials.Find(id);
        string name = fileToDownload.filepath;
        Debug.WriteLine("filepath  " + name);
        try
        {

            if (!string.IsNullOrEmpty(name))
            {
                //var root = System.Web.HttpContext.Current.Server.MapPath(name);
                var filePath = System.Web.HttpContext.Current.Server.MapPath(name); ;
                char[] s = new char[name.Length - name.LastIndexOf("\\") - 1];
                name.CopyTo(name.LastIndexOf("\\")+1, s, 0, name.Length - name.LastIndexOf("\\")-1);
                String fileName = new String(s);
                using (MemoryStream ms = new MemoryStream())
                {
                    using (FileStream file = new FileStream(name, FileMode.Open, FileAccess.Read))
                    {
                        Debug.WriteLine("file  " + file.Length);
                        byte[] bytes = new byte[file.Length];
                        file.Read(bytes, 0, (int)file.Length);
                        ms.Write(bytes, 0, (int)file.Length);

                        HttpResponseMessage httpResponseMessage = new HttpResponseMessage();
                        ByteArrayContent content = new ByteArrayContent(bytes.ToArray());
                        httpResponseMessage.Content = content;
                        httpResponseMessage.Content.Headers.Add("x-filename", fileName);
                        httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                        httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
                        httpResponseMessage.Content.Headers.ContentDisposition.FileName = fileName;
                        httpResponseMessage.StatusCode = HttpStatusCode.OK;
                        return httpResponseMessage;
                    }
                }
            }
            return null;
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.Data);
            return null;
        }
    }
                $http({
                    method: 'POST',
                    url: 'Download',
                    data: { 'name': file.filepath },
                    responseType: 'arraybuffer'
                }).success(function (content, status, headers) {
                    headers = headers();
                    console.log(content);
                    console.log(status)
                    var filename = headers['x-filename'];
                    var contentType = headers['content-type'];

                    var linkElement = document.createElement('a');
                    try {
                        var blob = new Blob([content], { type: contentType });
                        console.log(blob);
                        var url = URL.createObjectURL(blob);
                        console.log(url)
                        linkElement.setAttribute('href', url);
                        linkElement.setAttribute("download", filename);

                        var clickEvent = new MouseEvent("click", {
                            "view": window,
                            "bubbles": true,
                            "cancelable": false
                        });
                        linkElement.dispatchEvent(clickEvent);
                    } catch (ex) {
                        console.log(ex);
                    }
                }).error(function (data) {
                    console.log(data);
                });
            };
问题是我得到了一个未定义的空文件。我调试了代码,代码运行良好,来自asp控制器的数据在HttpResponse中结构良好

我能做些什么使它工作。欢迎提供任何其他让下载正常运行的建议

编辑:

我更改了asp.net控制器中的下载功能。我使用了HttpResponseMessage类。在解决方案中,我使用了Response类

asp控制器现在是:

    [HttpPost]
    public void Download(String name)
    {
        Debug.WriteLine("filepath  " + name);

            if (!string.IsNullOrEmpty(name))
            {
                char[] s = new char[name.Length - name.LastIndexOf("\\") - 1];
                name.CopyTo(name.LastIndexOf("\\")+1, s, 0, name.Length - name.LastIndexOf("\\")-1);
                String fileName = new String(s);
                //var filePath = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/") + fileName;

                Response.ContentType = "application/octet-stream";

                Response.AppendHeader("Content-Disposition", fileName);
                Response.AppendHeader("X-FileName", fileName);
                Response.TransmitFile(name);
                Response.End();

                }

    }

angular.identity
阻止angular对我们的数据执行任何操作(如序列化数据)。

感谢您的回答,但这给了我此错误无效的JSON原语:object。说明:在执行当前web请求期间发生未经处理的异常。请查看堆栈跟踪以了解有关错误的详细信息及其在代码中的起源。I get“Object不支持此var clickEvent=new MouseEvent上的此操作”(“单击“,{“查看”:窗口,“气泡”:true,“可取消”:false});
            }).