C# 在MVC 5中上载文件时出现空引用异常
我正在为一个使用MVC5和实体框架的网站开发CMS。我有一个编辑表单,用于编辑数据库表中添加的事件。我正在将与事件相关的图像上载到服务器文件夹中,并将其URL存储在数据库中 现在我想换一个新的C# 在MVC 5中上载文件时出现空引用异常,c#,asp.net-mvc,file-upload,C#,Asp.net Mvc,File Upload,我正在为一个使用MVC5和实体框架的网站开发CMS。我有一个编辑表单,用于编辑数据库表中添加的事件。我正在将与事件相关的图像上载到服务器文件夹中,并将其URL存储在数据库中 现在我想换一个新的 @Html.EditorFor(model => model.Image_Url, new { htmlAttributes = new { @class = "form-control" } }) 使用类型为File的输入,以便任何人都可以在编辑事件信息时更改图像。为此,我添加了以下内容 A图片
@Html.EditorFor(model => model.Image_Url, new { htmlAttributes = new { @class = "form-control" } })
使用类型为File
的输入,以便任何人都可以在编辑事件信息时更改图像。为此,我添加了以下内容
A图片
类
public class Pictures
{
public HttpPostedFileBase File { get; set; }
}
用于在控制器的编辑操作方法中上载文件
if (picture.File.ContentLength > 0)
{
var fileName = Path.GetFileName(picture.File.FileName);
var path = Path.Combine(Server.MapPath("~/assets/uploads/events/"), fileName);
picture.File.SaveAs(path);
filePath = "~/assets/uploads/events/" + fileName;
}
最后在Edit
视图中
<input type="file" id="File" name="File" class="form-control" />
在Create
action方法中使用上述逻辑时,效果非常好,但在编辑操作方法中使用相同的逻辑时,会出现Null引用异常。调试时,我发现picture.File
参数在if(picture.File.ContentLength>0)
行为空
这在Create
中运行良好,但在Edit
操作方法中返回null
有关此问题的任何帮助?由于无法为
设置值,因此可能会出现此问题。因此,我认为您唯一能做的就是创建一个单独的视图,以便为配置文件重新创建图像,并且每次用户向您发送图片时,都是一张新图片。我使用Request.Files
完成了此操作。下面是我在控制器编辑操作方法中的代码
foreach(string fileName in Request.Files)
{
HttpPostedFileBase file = Request.Files[fileName];
fName = file.FileName;
if (file != null && file.ContentLength > 0)
{
var orgDirectory = new DirectoryInfo(Server.MapPath("~/assets/uploads"));
string pathString = System.IO.Path.Combine(orgDirectory.ToString(),"events");
var fileName1 = Path.GetFileName(file.FileName);
bool isExists = System.IO.Directory.Exists(pathString);
if(!isExists)
{
System.IO.Directory.CreateDirectory(pathString);
}
var path = string.Format("{0}\\{1}", pathString, file.FileName); //pathString + file.FileName;
file.SaveAs(path);
}
}
您能否尝试在操作中使用Request.Files
。是的,您是对的。无法为“”设置值。我尝试过@Ehsan Sajjad建议,它对我很有效。