Anup
Anup

Reputation: 9746

MVC - Upload document with ajax call

I am using the following code to upload documents. I am using ajax in this scenario.

In the following code i get Request.Files.Count as 0. Therefore the file doesn't get uploaded.

Front-end code:

<input type="file" name="name" id="pd-fileName" />
....
<button class="btn pr-btn" id="pd-addBtn" type="button" onclick="insertDocument()">Add</button>

function insertDocument() {
              ......

        jq.post('/Main/addDocument?Id=' + Id , function (data) {                
                alert('Data saved successfully.!');

              ......
            });

        });
    }

Code in the controller:

[HttpPost]
public JsonResult addDocument(int Id)
{
    string pathPhysical = Server.MapPath("~/Documents/" + Id + "/");
    if (!Directory.Exists(pathPhysical))
    {
        DirectoryInfo di = Directory.CreateDirectory(pathPhysical);
    }

    if (Request.Files.Count > 0)
    {
        var file = Request.Files[0];

        if (file != null && file.ContentLength > 0)
        {
            var documentName = Path.GetFileName(file.FileName);
            pathPhysical = Path.Combine(pathPhysical, documentName);
            file.SaveAs(pathPhysical);
        }
    }

    return Json(JsonRequestBehavior.AllowGet);
}

How do I solve this?

Upvotes: 0

Views: 241

Answers (2)

CE ZHANG
CE ZHANG

Reputation: 527

Try this:

<input id="pd-fileName" type="file" name="myfiles[]" multiple="multiple" />

var myfiles = document.getElementById("pd-fileName");
        var files = myfiles.files;
        var data = new FormData();

        for (i = 0; i < files.length; i++) {
            data.append('file' + i, files[i]);
        }

$.ajax({
  beforeSend:function(){...},
  type:'post',
  url:'you url here',
  data:data,
  processData:false,  // Tell jquery not to process data into any format
  success:function(){...},
  complete:function(){...}
});

Upvotes: 1

Tushar Gupta
Tushar Gupta

Reputation: 15933

For MVC you need a HttpPostedFileBase object in your controller to catch the file, the following example might help you,

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

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

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

Note: for UPload: enctype="multipart/form-data" is a prerequisite.


At 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);
  }

  return RedirectToAction("Index");
}

Notice that the argument to the action method is an instance of HttpPostedFileBase.

Upvotes: 0

Related Questions