0

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?

2 Answers 2

1

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(){...}
});
Sign up to request clarification or add additional context in comments.

4 Comments

How to pass data value?
Just for record, this method does NOT work in IE8 or below. If you really need this, you should do a little 'hacking'.
@Anup, for passing data value, FormData object works fine. var formData=new FormData(); formData.append('file here'). But this object isn't supported by IE8.
0

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.

1 Comment

Your code with refresh the page... as i need to use ajax....i cannot use submit button with type submit...!

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.