سؤال

I am doing something wrong here, but not able to figure it out. I have a virtual directory and a files inside it and I want to download the file.

My code:

public ActionResult DownloadFile()
{
    string FileName = Request.Params["IMS_FILE_NAME"];
    string FullFileLogicalPath = Path.Combine(ConfigurationManager.AppSettings["VIRTUAL_DIR_PATH"], FileName);
    string FullfilePhysicalPath = Path.Combine(ConfigurationManager.AppSettings["PHYSICAL_DIR_PATH"], FileName);
    if (System.IO.File.Exists(FullfilePhysicalPath))
    {
        return File( FullFileLogicalPath , "Application/pdf", DateTime.Now.ToLongTimeString());
    }
    else
    {
        return Json(new { Success = "false" });
    }
}

I am getting an error:

http:/localhost/Images/PDF/150763-3.pdf is not a valid virtual path.

If I post this URL http:/localhost/Images/PDF/150763-3.pdf in my browser, the file is opened. How can I download this file?

Platform MVC 4, IIS 8.

هل كانت مفيدة؟

المحلول

It should be http://localhost/Images/PDF/150763-3.pdf (instead of http:/)

Chrome will change http:/ to http:// but your program will not.


I think I misread your question.

Try (fixed from comment)

return File(FullfilePhysicalPath, "Application/pdf", DateTime.Now.ToLongTimeString()+".pdf");

نصائح أخرى

If you want use routes url in format: "{controller}/{action}/{id}":

There is class RouteConfig defined ~/App_Start/RouteConfig.cs in MVC 4 You have ImageController and PDF action and 150763-3.pdf is the parameter id.

http://localhost/Images/PDF/150763-3.pdf

Solution is very simple:

public class ImagesController : Controller
    {
        [ActionName("PDF")]
        public ActionResult DownloadFile(string id)
        {
            if (id == null)
                return new HttpNotFoundResult();

            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
            string FileName = id;

            string FullFileLogicalPath = Path.Combine(ConfigurationManager.AppSettings["VIRTUAL_DIR_PATH"], FileName);
            string FullfilePhysicalPath = Path.Combine(ConfigurationManager.AppSettings["PHYSICAL_DIR_PATH"], FileName);
            if (System.IO.File.Exists(FullfilePhysicalPath))
            {
                return File(FullFileLogicalPath, "Application/pdf", FileName);
            }
            else
            {
                return Json(new { Success = "false" });
            }

        }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top