在 MVC 5 中上传文件时出现空引用异常
本文关键字:引用 异常 文件 MVC | 更新日期: 2023-09-27 18:31:57
我正在使用MVC 5和实体框架为网站开发CMS。我有一个编辑表单,用于编辑数据库表中添加的事件。我正在服务器文件夹中上传与事件相关的图像,并将其URL存储在数据库中。
现在我想替换
@Html.EditorFor(model => model.Image_Url, new { htmlAttributes = new { @class = "form-control" } })
使用类型 File
的输入,以便任何人都可以在编辑事件信息时更改图像。 为此,我添加了以下内容。
Picture
类
public class Pictures
{
public HttpPostedFileBase File { get; set; }
}
用于在控制器Edit Action Method
上传文件
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
操作方法中使用时工作得很好,但是当我在编辑操作方法中使用相同的逻辑时,Null reference exception
发生。调试时,我发现picture.File
参数在第 if (picture.File.ContentLength > 0)
行为 null。
这在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);
}
}
此问题可能是由于<input type="file" />
的一般安全规则,因为您无法为其设置值。所以我认为您唯一能做的就是为配置文件重新创建图像创建单独的视图,并且每次用户向您发送图片时都会收到一张新图片。