2

I used file upload to insert the file path on DB and the uploaded file on file on the project directory , I added my code but It didn't worked well.

<div class="editor-field create-Bt2">
        @Html.EditorFor(model => model.Active)
        @Html.ValidationMessageFor(model => model.Active)
    </div>
    <div>
        <p class="create-Bt ">
            <input type="submit" value="Create" />
        </p>
    </div>

[HttpPost]
    public ActionResult Create(Category category)
    {
        if (ModelState.IsValid)
        {
            var fileName = "";

            var fileSavePath = "";
            var uploadedFile = Request.Files[0];
            fileName = Path.GetFileName(uploadedFile.FileName);
            fileSavePath = Server.MapPath("../../Uploads/" +
              fileName);
            uploadedFile.SaveAs(fileSavePath);


            db.Categories.Add(category);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(category);
    }
2
  • 1
    "It didn't work well". What went wrong? Are you not getting a file, doesnt it hit the action, what is happening? Commented Nov 21, 2012 at 8:55
  • It didn't worked well. Please describe precisely what happend! Error code, actual behavior, etC. Commented Nov 21, 2012 at 8:56

1 Answer 1

3

On your form

<form action="" method="post" enctype="multipart/form-data">

  <label for="file">Filename:</label>
  <input type="file" name="file" id="file" />

  <input type="submit" />
</form>

In your Controller

[HttpPost]
public ActionResult Index(HttpPostedFileBase file) {

  if (file.ContentLength > 0) {
    var fileName = Path.GetFileName(file.FileName);
    var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
    file.SaveAs(path);

    // save the path to your table 
    // db.???

    db.SaveChanges();


  }

  return RedirectToAction("Index");
}
Sign up to request clarification or add additional context in comments.

3 Comments

I can't see how you've changed it. the point of my answer it that if you want to receive a file you MUST have a parameter of type HttpPostedFileBase that is called whatever your file input control is called.
I used Razor also I didnot post all completed project ,the page has input button
but you understand that my answer is how you achieve what you are trying to do. You should mark it correct and upvote it if you agree.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.