Tuta Tuta - 1 year ago 135
ASP.NET (C#) Question

Delete Uploaded file in MVC5?

I'm working with an MVC5 project, I have created a simple system that the user can upload a file "CV" for each Employee.
Now all thing work for me fine except "DELETING File".
I need to add action method for deleting uploaded file and the ability to replace it with another file.

in the model class I have created two property HttpPostedFileBase CV to save the uploaded file
and String cvName, to save the file name and use it to create a link to that file.

In the controller that what I have done:

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))
//Session["DeleteSuccess"] = "Yes";
return RedirectToAction("Index");

and this is the view:

<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" />
<input type="file" name="file" accept="pdf" />

I can't delete the file, each time this message appears

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

Answer Source

You're sending a GET to a POST

Change the [HttpPost] to [HttpGet]

Or use JQuery and send a DELETE verb like I mentioned in the comments

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download