Reputation: 9
I have a mvc 5 application, I save letters files in folder inside folder like (~\Files\Letters) and I save the physical path in database, uploading letters files to (~\Files\Letters) works fine and saving the physical path works fine, the problem is downloading a letter file to client machine, I have tried using Webclient and Response both don't work and don't give any error, here is the code for downloading a letter file using Response.
[HttpPost]
public void open(int id)
{
string path = "";
path = db.tblLetters.Where(t => t.ID == id).SingleOrDefault().LetterImg;
string fileName = path.Substring(path.LastIndexOf(@"\")+1);
string p = Server.MapPath("~/Files/LettersImgs/" + fileName);
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
Response.ContentType = "application/octet-stream";
Response.TransmitFile(p);
Response.End();
}
Upvotes: 1
Views: 1713
Reputation: 24957
Rather than using old-style Response.TransmitFile
, you can use FilePathResult
to return file directly from server's file path. Change return type from void
to ActionResult
(or FileResult
) and use [HttpGet]
instead of [HttpPost]
, and do return File(...)
to let user download the file like this example below:
[HttpGet]
public ActionResult Open(int id)
{
string path = "";
path = db.tblLetters.Where(t => t.ID == id).SingleOrDefault().LetterImg;
string fileName = path.Substring(path.LastIndexOf(@"\")+1);
string p = Server.MapPath("~/Files/LettersImgs/" + fileName);
return File(p, "application/octet-stream", fileName);
}
Related issue: How to download a file to client from server?
Upvotes: 2