Kamlesh Kumar
Kamlesh Kumar

Reputation: 3

I want to download my Pdf File in server path in mvc please any one guide me... with code

what is the controller code. how can i set the path of the server folder.

string path = HttpContext.Server.MapPath("~/Areas/CreatePaperSet/PdfPaperSet");
HttpContext.Response.TransmitFile(path);


WebClient client = new WebClient();
byte[] buffer = client.DownloadData(path);
if (buffer != null)
{
    Response.Clear();
    Response.ContentType = "application/pdf";
    Response.AddHeader("content-disposition", "attachment;filename=DownloadPaperSet.pdf");
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.BinaryWrite(buffer);
    Response.End();

}


pdfDoc.Close();

Upvotes: 0

Views: 4489

Answers (1)

Hien Nguyen
Hien Nguyen

Reputation: 18975

This is my way to download file in folder and it worked.

You can create an Action with fileName as parameter. In action you read file as byte[] and return File object.

public ActionResult Download(string fileName)
{
    string path = Server.MapPath("~/Content/PdfPaperSet");
           
    byte[] fileBytes = System.IO.File.ReadAllBytes(path + @"\" + fileName);
            
    return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}

In your cshtml file, pass fileName = "yourfile.pdf" as parameter.

@Html.ActionLink("Download Your File", "Download", new { fileName = "yourfile.pdf" })

Beware of Path Traversal Attacks by adding some additional argument validation checks:

// Guard against Path Traversal Attacks:
var extension = Path.GetExtension(fileName);
if (!string.Equals(extension, ".pdf"))
    return BadRequest();

var extractedFileName = Path.GetFileName(fileName);
if (fileName != extractedFileName)
    return BadRequest();

Upvotes: 1

Related Questions