Join the Stack Overflow Community
Stack Overflow is a community of 6.6 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I want to download a file from the server, but I don't understand what I'm doing wrong. I've been searching how to do it, but doesn't work. This is an example that I found:

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

When I load the file I just get the filename incomplete "aae49c8e-c523-4ccc-a7ba-88f405072047" and don't load the file. Thanks for any help.

share|improve this question

Stream the file from the server:

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

Open new window with URL to action method that will STREAM the PDF so that it can be shown in the browser:

var fileURL = 'serv/Consultas/GetFile?filename=file.pdf';
$window.open(fileURL);
share|improve this answer
    
I've changed the name to probe your suggestion, but I could see that I get this: "localhost:58334/53464c98-71b5-4e3c-afd7-0ad334490255" when I try to load the file and I just sent: var filename = "file.pdf" I guess my problem is in angular controller, do you have an example to receive a file and download? – Edith Capistran Sep 23 '16 at 16:50
    
From your angular code, it appears that you are downloading the PDF file, then converting it and having it show in a window. I'm assuming you are doing this so the user can view the PDF on a browser. Is this correct? – Andrés Nava - .NET Sep 23 '16 at 17:08
    
Yes, I want to show in a View the PDF file. Another option is just download the pdf file with a simple link. – Edith Capistran Sep 23 '16 at 17:26
    
I think what you want to do is simply open the window and have the server stream the file from the server instead of download it. I've updated my answer. Notice the return type of the action method is FileStreamResult and I'm directly returning a File and I do not specify a fileName for the returned stream. If you do specify a fileName, it will prompt the user to download it. – Andrés Nava - .NET Sep 23 '16 at 17:39
    
Thanks Andrés, It works =) I've put the url in a hyperlink <a target="_blank" href="/serv/Consultas/GetFile?filename={{PerfilVM.ActaNacimi‌​entoDir}}" download>link</a>, just one question more, how can I force the browser to show the "Safe as.." dialog? – Edith Capistran Sep 23 '16 at 19:20

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.