3

I tried using the below code. But it did not work.

public FileResult download(string path)
{
   return File(path, "application/pdf", Server.UrlEncode(path));
}

My Ajax Code is:

function fileDownload(path) { 
    $.ajax({ 
       url: '/Home/download', 
       data: { path: path }, 
       type: 'POST', 
       async: false, 
       success: function (data) { } 
    }); 
}
1
  • Did code hit the controller ? Commented Dec 15, 2014 at 6:57

4 Answers 4

4

You'll generally want to map the file name to a physical path on the server, e.g. assuming the user selects the file Foo.pdf and all content files are in the ~/Content folder:

public FileResult download(string path)
{ 
    string actualPath = Server.MapPath("~/Content/" + path);
    return File(actualPath, "application/pdf", Server.UrlEncode(path)); 
}

However, from a security viewpoint, allowing a user to directly specify a file name is dubious - you may instead want to consider other alternatives, such as a table or dictionary of available files, and force the browser to select one of the available files via key - this way malicious users can't phish for files which weren't meant to be served.

Edit, after seeing that OP wants to Ajax

Ajaxing the document down should work, although downloading in this way won't render the PDF - you would need to pass the document to a scriptable PDF viewer or similar.

Instead of ajaxing the document, you can instead generate a simple link, button or image which the user can click on to invoke the controller action and download the PDF:

 @Html.ActionLink("Click to download", "download", new {path = "MyNicePDF.pdf"})
Sign up to request clarification or add additional context in comments.

1 Comment

@HardikMansaraa you will need to qualify Did not Work. Rendered no file? Gave you an error? etc
1
function DownloadAndReturnBackAttachment(linkHref) {

    $.fileDownload(linkHref, {

        successCallback: function (url) {
            gvScanDocuments.PerformCallback();
            gvScanDocuments.UnselectRows();

        },

        failCallback: function (url) {
            alert("A file download error has occurred, please try again.");
            gvScanDocuments.PerformCallback();
            gvScanDocuments.UnselectRows();

        }

    });
} 

Comments

1

This task is complete using window.location method.

Also You can use HTML tag for this:

<a href="Path" download="Filename">download me</a>

Comments

0
public FileResult Download(string path)
{
      byte[] fileBytes = System.IO.File.ReadAllBytes(path);
      string fileName = "your file name";
      return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);         
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.