Uploading a file with asp.net mvc

I tried using the below code. But it didn't work.

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

      

My Ajax code:

function fileDownload(path) { 
    $.ajax({ 
       url: '/Home/download', 
       data: { path: path }, 
       type: 'POST', 
       async: false, 
       success: function (data) { } 
    }); 
}

      

+3


source to share


3 answers


This task is completed using the window.location method.

Also you can use HTML tag for this:



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

      

+1


source


Usually you want to map a filename to a physical path on the server, eg. assuming the user selects a file Foo.pdf

and all content files are in the folder ~/Content

:

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

      

However, from a security point of view allowing the user to directly specify a filename, it is questionable - instead, you might 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 a key - this way attackers cannot phish for files that are not intended for service.

Edit after seeing OP wants Ajax



Ajaxing the document down should work, although loading this way will not show up in PDF - you will need to feed the document to a PDF viewer script or similar.

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

 @Html.ActionLink("Click to download", "download", new {path = "MyNicePDF.pdf"})

      

+4


source


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

        }

    });
} 

      

+1


source







All Articles