我试图在我的应用程序文件夹之外获取一个文件来下载...
public FilePathResult DownloadFile(Guid id, string dateiname)
{
string pfad = @"D:\wwwroot\portal_Daten\";
return File(pfad + dateiname, "application/pdf", dateiname);
}
错误消息:是D:\ wwwroot \ portal_Daten \ 8/0/6 / a / e / 974-aaca-426c-b7fc-e6af6c0fb52e / oeffentlich是物理路径,但它是预期的虚拟路径。
为什么这不能用物理路径工作?我怎样才能将其变为虚拟路径?
此致 浮
答案 0 :(得分:2)
我在路径中处理这个的方法是使用自定义文件下载http处理程序(对于asp.net webforms应用程序),你可以在这里使用相同的。你甚至可以构造一个新的ActionResult子类,它可能会给你带来相同的结果。
我这样做的方法是创建IHttpHandler的实现,处理请求并返回文件。这样您就不会受限于使用虚拟路径,只要您的Web服务器安全配置允许,您就可以访问系统上的任何文件并将其返回给浏览器。
类似的东西:
public class MyFileHandler : IHttpHandler
{
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
string filePath = Path.Combine(@"d:\wwwroot\portal_daten", context.Request.QueryString["dateiname"]);
context.Response.ContentType = "application/pdf";
context.Response.WriteFile(filePath);
}
}
一个没有检查的精简示例,但是你可以填写。然后在你的web.config中注册处理程序:
<handlers>
<add name="MyFileHandler" path="file.axd" type="MvcApplication4.Models.MyFileHandler" verb="GET" />
</handlers>
您当然必须重命名类/命名空间以适合自己。然后,该文件的实际Web链接将变为:
http://[domain]/file.axd?dateiname=mypdf.pdf
[domain]是您的域名/ localhost或您正在使用的任何内容。
答案 1 :(得分:0)
你需要使用Server.MapPath并给它一个文件位置,以便它可以将路径映射到服务器上的相对目录
类似
public FilePathResult DownloadFile(Guid id, string dateiname)
{
string pfad = Server.MapPath(@"D:\wwwroot\portal_Daten\");
var filePath = Path.Combine(pfad, dateiname);
return File(filePath , "application/pdf", dateiname);
}
应该有效