我想为我的上传文件进行表单编辑,所以我想在上传新文件后删除文件
这是我的RazorView
@model updownload.Models.updown
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.HiddenFor(x => x.id)
<div class="container">
<div>
@Html.ValidationMessage("uploadError")
@Html.TextBoxFor(x => x.upload, new { type = "file", id = "file" })
</div>
<div class="form-group">
<label>Username:</label>
@Html.TextBoxFor(x => x.keterangan)
</div>
<div class="button">
<button>Submit</button>
</div>
</div>
}
这是我的编辑控制器
[HttpPost]
public ActionResult Edit(updown viewModel, HttpPostedFileBase file)
{
var currentupdown = db.updowns.Find(viewModel.id);
if (viewModel.upload != null)
{
System.IO.File.Delete(Path.Combine(Server.MapPath("~/App_Data/upload"), viewModel.upload));
string fileName = Guid.NewGuid() + Path.GetFileName(file.FileName);
string path = Path.Combine(Server.MapPath("~/App_Data/upload"), fileName);
file.SaveAs(path);
viewModel.upload = fileName;
}
else
{
currentupdown.upload = currentupdown.upload;
}
currentupdown.keterangan = viewModel.keterangan;
db.SaveChanges();
return RedirectToAction("List", "Home");
}
我在这行string fileName = Guid.NewGuid() + Path.GetFileName(file.FileName);
请有人修复我的代码。 抱歉我的英文不好
答案 0 :(得分:1)
您收到一个典型的空引用异常,因为file
为NULL
而您正试图访问该FileName
属性。
为什么文件为空?
要从表单上传文件,表单应具有enctype
属性,其值设置为"multipart/form-data"
。您当前的视图代码将生成不带该表单的表单标记。
<form action="/Home/Edit" method="post">
</form>
首先修复它。另外,要使文件上传起作用,文件输入元素的名称属性值必须与HttpPostedFileBase
参数的名称匹配。
@using (Html.BeginForm("Edit", "Home", FormMethod.Post,
new { enctype = "multipart/form-data"}))
{
@Html.LabelFor(a => a.keterangan)
@Html.TextBoxFor(a => a.keterangan)
@Html.HiddenFor(x => x.id)
<input type="file" name="file"/>
<input value="submit" type="submit" class="btn" />
}
这将呈现发送文件所需的正确HTML标记。
现在,在服务器操作方法中,您需要在尝试访问file
参数之前对[HttpPost]
public ActionResult Edit(updown viewModel, HttpPostedFileBase file)
{
var currentupdown = db.updowns.Find(viewModel.id);
if (file != null)
{
var location=Server.MapPath("~/App_Data/upload");
//Delete existing file
if (!string.IsNullOrEmpty(currentupdown.upload))
{
var existingFile= Path.Combine(location, currentupdown.upload);
if (System.IO.File.Exists(existingFile))
{
System.IO.File.Delete(existingFile);
}
}
var fileName = Guid.NewGuid() + Path.GetFileName(file.FileName);
var path = Path.Combine(location, fileName);
file.SaveAs(path);
currentupdown.upload = fileName; // Update to the new file name
}
currentupdown.keterangan = viewModel.keterangan;
db.SaveChanges();
return RedirectToAction("List", "Home");
}
参数进行空检查。
File
由于您有一个视图模型,您还可以向名为HttpPostedFileBase
(类型为if(file!=null)
)的视图模型中添加一个新属性,并在您的服务器操作中使用它。使用此功能,您可以删除第二个参数,因为您的视图模型已具有此属性。因此,不是检查if(viewmodel.File!=null)
,而是执行public class YourViewModel
{
public int Id { set;get;}
public string Keterangan { set;get;}
public HttpPostedFileBase File { set;get;}
}
[HttpPost]
public ActionResult Edit(YourViewModel viewModel)
{
// use viewModel.File as needed
}
和
{{1}}