2013-05-16 100 views
2

我在这里做错了什么,但无法弄清楚。我有一个虚拟目录和一个文件在里面,我想下载文件。从虚拟目录下载文件

我的代码:

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" }); 
    } 
} 

我得到一个错误:

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

如果我在我的浏览器发布此URL http:/localhost/Images/PDF/150763-3.pdf,文件被打开。我怎样才能下载这个文件?

平台MVC 4,IIS 8

+0

在你的代码的行,你得到这个错误? –

+0

在Application.Error() –

+0

方法中的Global.asax中出现错误使用IIS 7.5可以正常工作。 – misak

回答

0

它应该是(HTTP的,而不是:/)http://localhost/Images/PDF/150763-3.pdf

Chrome就会将http:/到http://但是你的程序将不会。


我想我误解了你的问题。

尝试(固定从评论)

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

如果我调试我的代码并将鼠标放在FullFileLogicalPath上(如果条件不变),它会显示“http:\\\\ localhost \\ Images \\ PDF \\ 150763-3.pdf”,如果我点击Button的工具提示,里面的文本展示它显示我http:\\ localhost \ Images \ PDF \ 150763-3.pdf那么问题在哪里?我在哪里错过了“/”? –

+0

我试过你的解决方案,在末尾追加“.pdf”,但它仍然不工作,在Global.asax Application_Error()方法我得到一个异常“http:/localhost/Images/PDF/150771-1.pdf”是不是有效的虚拟路径。我没有得到如何将http://转换为http:/? –

+1

你为什么不使用FullfilePhysicalPath? – laktak

0

如果你想使用的路由URL格式: “{控制器}/{行动}/{ID}”:

还有就是类RouteConfig定义〜 MVC中的/App_Start/RouteConfig.cs 4 您有ImageController和PDF操作,150763-3.pdf是参数ID。

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

解决方案很简单:

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" }); 
      } 

     } 
} 
+0

我做了同样的事情(把[ActionName(“PDF”)]放在我的动作上面),仍然显示出同样的错误“http:/ localhost/Images/PDF/150763- 3.pdf不是有效的虚拟路径。“ –

+0

很好奇。我的代码工作正常。 ......哪一行引发异常? – misak

+0

在Application.Error()方法中的Global.asax中出现错误 –