删除 MVC5 中上传的文件?

Delete Uploaded file in MVC5?

我正在处理一个 MVC5 项目,我创建了一个简单的系统,用户可以为每个员工上传一个文件“CV”。 现在除了“删除文件”之外,一切都对我有用。 我需要添加删除上传文件的操作方法以及用另一个文件替换它的能力。

在模型中class我创建了两个属性HttpPostedFileBase CV来保存上传的文件 和 String cvName,用于保存文件名并使用它为该文件创建 link。

在我所做的控制器中:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult DeleteCV(string cvName)
{
    //Session["DeleteSuccess"] = "No";
    var CVName = "";
    CVName = cvName;
    string fullPath = Request.MapPath("~/Content/CVs/" + CVName);

    if (System.IO.File.Exists(fullPath))
    {
        System.IO.File.Delete(fullPath);
        //Session["DeleteSuccess"] = "Yes";
    }
    return RedirectToAction("Index");
} 

这是视图:

<div class="form-group">
    @Html.LabelFor(model => model.CV, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @{
            if (File.Exists(Server.MapPath("~/Content/CVs/"
             + Html.DisplayFor(model => model.cvName))))
            {
                <a href="~/Content/CVs/@Html.DisplayFor(model => model.cvName)"> @Html.DisplayFor(model => model.cvName)  @Html.HiddenFor(model => model.cvName)</a>
                <a href="@Url.Action("DeleteCV", new { @Model.cvName })">
                    <img src="@Url.Content("~/Content/Images/Delete.jpg")" width="20" height="20" class="img-rounded" />
                </a>
            }
            else
            {
                <input type="file" name="file" accept="pdf" />
            }
        }
    </div>
</div> 

我无法删除文件,每次出现此消息

The resource cannot be found.

Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.

Requested URL: /DeleteCV

您正在向 POST

发送 GET

[HttpPost] 更改为 [HttpGet]

或者使用 JQuery 并像我在评论中提到的那样发送 DELETE 动词

您正在使用 <a href="@Url.Action("DeleteCV", new { @Model.cvName })"></a>,因此您的 link 将变为 /Controller/DeleteCV?cvName=SomeName,它将作为 GET 执行。出于多种原因您不希望这样做,坦率地说,其余代码也一团糟。不要在您的视图中执行业务逻辑(例如检查文件),并且您可能想要围绕 File.Delete().

添加一些检查

在控制器中检查文件,将结果保存在模型变量中,并创建一个单独的表单 POST 到您的 Delete 方法:

if (@Model.FileExists)
{
    @using(Html.BeginForm("Cv", "DeleteCV", FormMethod.Post))
    {
        @Html.AntiForgeryToken()
        @Html.HiddenFor(m => m.cvName)
        <input type="submit" value="Delete" />
    }
}
else
{
    @using(Html.BeginForm("Cv", "UploadCV", FormMethod.Post))
    {
        @Html.AntiForgeryToken()
        <input type="file" name="file" accept="pdf" />
        <input type="submit" value="Upload" />
    }
}