【问题标题】:Unable to load the file in MVC无法在 MVC 中加载文件
【发布时间】:2011-08-23 11:31:30
【问题描述】:
我有下一个代码:
var ordinaryPropertyValue = new Catalog.Core.Entities.OrdinaryPropertyValue();
Environment.CurrentDirectory = System.IO.Path.GetTempPath();
var fileFile = Request.Files["File" + prop.Id];
if (fileFile == null) continue;
string pathFile = Environment.CurrentDirectory;
fileFile.SaveAs(pathFile);
ordinaryPropertyValue.Value = pathFile;
instance.SetPropertyValue(prop.Id, ordinaryPropertyValue);
但我无法加载我的文件,因为下一个问题:
AccessException:对路径“C:\Users\Michael\AppData\Local\Temp”的访问被拒绝。
【问题讨论】:
标签:
c#
asp.net
asp.net-mvc
file-upload
http-post
【解决方案1】:
这是一个安全例外,您的 Web 应用程序的执行用户无权在目标路径上写入。
请注意,您正在尝试将文件保存到没有文件名的目录路径。
无论如何,您的代码都是一团糟,我个人不分配/更改Environment.CurrentDirectory
【解决方案2】:
我假设您在本地计算机上使用 IIS,在这种情况下,您可能需要将此目录的写入权限授予运行 Web 应用程序的帐户(使用 VS 的内置服务器在您的帐户下运行) .
如果您使用的是 IIS 7 +,则为“ApplicationPoolIdentity”,否则为“NETWORK SERVICE”
附:我也不建议更改环境设置。
【解决方案3】:
感谢您的帮助,但正如您所说,真正的原因不是访问问题。
真正的原因是空的 "" 值。所以我重新制作了我的代码,例如:
var ordinaryPropertyValue = new Catalog.Core.Entities.OrdinaryPropertyValue();
var fileFile = Request.Files["File" + prop.Id];
if (fileFile == null)
continue;
string pathFile = Server.MapPath("~/temp");
string filenameFile = Path.GetFileName(fileFile.FileName);
if (!string.IsNullOrEmpty(filenameFile))
{
fileFile.SaveAs(Path.Combine(pathFile, filenameFile));
ordinaryPropertyValue.Value = Path.Combine(pathFile, filenameFile);
instance.SetPropertyValue(prop.Id, ordinaryPropertyValue);
}