Reputation: 3376
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) { }
});
}
Upvotes: 3
Views: 8309
Reputation: 121
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);
}
Upvotes: 0
Reputation: 3376
This task is complete using window.location method.
Also You can use HTML tag for this:
<a href="Path" download="Filename">download me</a>
Upvotes: 1
Reputation: 17
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();
}
});
}
Upvotes: 1
Reputation: 107357
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"})
Upvotes: 4