1

I'm a beginner in developing using asp.net mvc. I'm trying to download files (images, pdf..) Here is my code

in the asp controller

    [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;
        }
    }

and in the angular controller

                $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);
                });
            };

The problem is I get an undefined and an empty file. I debugged the code it works fine, the data from the asp controller is well structured int the HttpResponse.

What can I do to make it work. Any other suggestions to get the download to function are welcomed.

Edit:

I changed the download funtion in the asp.net controller. I used the HttpResponseMessage class. In the solution, I used the Response class.

the asp controller is now :

    [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();

                }

    }
1
  • I get 'Object doesn't suppor this action on this var clickEvent = new MouseEvent("click", { "view": window, "bubbles": true, "cancelable": false }); Commented Mar 3, 2017 at 21:50

1 Answer 1

2
         $http({
                method: 'POST',
                url: 'Download',
                data: { 'name': file.filepath },
                responseType: 'arraybuffer',
                transformRequest: angular.identity,
            }).

angular.identity prevents Angular to do anything on our data (like serializing it).

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your answer but this gave me this error Invalid JSON primitive: object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.