大家好,我有一个上传功能,用户可以上传文件,我在插入数据库之前在表格中显示上传的文件,如果用户想要删除他想要的任何上传文件,我会在表格中提供删除选项..我正在尝试这段代码,但是文件没有被删除
这是我的文件上传代码
public ActionResult UploadFile(string AttachmentName, BugModel model)
{
BugModel bug = null;
if (Session["CaptureData"] == null)
{
bug = model;
}
else
{
bug = (BugModel)Session["CaptureData"];
}
foreach (string inputTagName in Request.Files)
{
HttpPostedFileBase file1 = Request.Files[inputTagName];
if (file1.ContentLength > 0)
{
BugAttachment attachment = new BugAttachment();
var allowedExtensions = new[] { ".doc", ".xlsx", ".txt", ".jpeg", ".docx" };
var extension = Path.GetExtension(file1.FileName);
if (!allowedExtensions.Contains(extension))
{
model.ErrorMessage = "{ .doc, .xlsx, .txt, .jpeg }, files are allowed.... ";
}
else
{
string filename = Guid.NewGuid() + Path.GetFileName(file1.FileName);
string path = "/Content/UploadedFiles/" + filename;
string savedFileName = Path.Combine(Server.MapPath("~" + path));
file1.SaveAs(savedFileName);
attachment.FileName = "~" + path.ToString();
attachment.AttachmentName = AttachmentName;
attachment.AttachmentUrl = attachment.FileName;
bug.ListFile.Add(attachment);
model = bug;
}
Session["CaptureData"] = model;
}
}
ModelState.Clear();
return View("LoadBug", bug);
}
这是我在表格中显示上传文件的视图
<table align="center" class="gridtable" border="0" cellspacing="0" cellpadding="0">
<tr>
<th>
Attachment Name
</th>
<th>
Attachment Url
</th>
<th>
Action
</th>
</tr>
<% if (Model != null && Model.ListFile != null)
{ %>
<% foreach (var Emp in Model.ListFile)
{ %>
<tr class="Data">
<td >
<%:Emp.AttachmentName %>
</td>
<td >
<%: Emp.FileName %>
</td>
<td>
<%-- <%= Html.ActionLink("Delete", "Delete")%>--%>
<%:Html.ActionLink("Delete", "Delete", new { @FileName = Emp.FileName })%>
</td>
</tr>
<% } %>
<% } %>
</table>
这是我的删除代码
public ActionResult Delete(string FileName)
{
char DirSeparator = System.IO.Path.DirectorySeparatorChar;
string FilesPath = ";" + FileName;
string filenameonly = name + Path.GetFileName(FilesPath);
string FPath = "Content" + DirSeparator + "UploadedFiles" + DirSeparator + filenameonly;
// Don't do anything if there is no name
if (FileName.Length == 0) return View();
// Set our full path for deleting
string path = FilesPath + DirSeparator;
// Check if our file exists
if (System.IO.File.Exists(Path.GetFullPath(AppDomain.CurrentDomain.BaseDirectory + FPath)))
{
// Delete our file
System.IO.File.Delete(Path.GetFullPath(AppDomain.CurrentDomain.BaseDirectory + FPath));
}
return View("LoadBug", Bug);
}
public string name { get; set; }
public object Bug { get; set; }
}