【发布时间】:2017-03-06 09:45:22
【问题描述】:
我在 IIS 7.5 中有一个网站,并尝试将文件上传到位于另一个驱动器上的 Files 文件夹中。我将名为 files 的虚拟文件夹添加到 wwwroot 文件夹中。
那个虚拟文件夹路径是D:\files
我在控制器中上传的代码:
_env 变量为 IHostingEnvironment 并注入到 Constructor 中。
var filename = _env.WebRootPath + $@"\files\{model.JobID}.{model.FileExt}";
using (FileStream fs = System.IO.File.Create(filename))
{
AttachFile.CopyTo(fs);
fs.Flush();
}
它在本地工作,因为我在我的机器中获得了物理文件夹 wwwroot\files。但它在生产服务器上不起作用并出现以下错误:
An unhandled exception has occurred: Could not find a part of the path 'C:\inetpub\Mysite\wwwroot\files\111214.png'.
但我在 ASPNet 4.6.1 中有另一个网站,我使用 Server.MapPath 上传文件。它可以在那个网站上运行,我可以成功上传文件。
string SaveLocation = string.Format(@"{0}\{1}{2}", Server.MapPath("files"), JobID, FileExt);
根据这篇文章,它说 Server.MapPath 和 WebRootPath 是相似的。 http://www.mikesdotnetting.com/article/302/server-mappath-equivalent-in-asp-net-core
但是,在我看来,WebRootPath 只为我们提供了网站的 RootPath。它不接受评估给定 url 的参数,如 Server.MapPath。
您能否告诉我如何在生产服务器上上传文件,而不是在我的 .Net Core 应用程序中硬编码物理路径?
更新 1:
这是迄今为止我达到的最好的……我们可以通过这种方式访问或创建另一个虚拟 URL 以指向另一个位置。可以通过http://mysite/Files/abc.jpg访问
app.UseStaticFiles(new StaticFileOptions()
{
FileProvider = new PhysicalFileProvider(@"D:\Files"),
RequestPath = new PathString("/Files"),
});
但是,它只是只读 url,我无法使用 "/Files/newfile.jpg" 或 Path.Combine(_env.WebRootPath, "newfile.jpg") 上传到此路径,因为它实际上并不存在。
【问题讨论】:
-
WebRootPath 不知道 IIS vdirs,你必须通过 IWebHostBuilder.UseWebRoot(mywebroot) 直接配置它
-
你知道如何解决这个问题了吗?
-
@Ruchan 您可以使用“D:\mySharedfiles\”而不是IIS虚拟文件夹直接写入物理文件夹
标签: c# asp.net-mvc asp.net-core asp.net-core-mvc