Home > Software design >  How To Send File To Action With JQuery?
How To Send File To Action With JQuery?

Time:04-08

I want to send txt file to action and get text words count without submiting form.

my codes in action works well (this action get HttpPostedFileBase and using with stream reader return count)so problem is in View.

this is My Code in View to send file to view and get result:

<script>

    $("#MyForm").submit(function (event) {
        event.preventDefault();

        var files = $('#fileInput').files[0]);

        $.ajax({
            type: "Post",
            url: "/Counter/GetCount",
            enctype: "multipart/form-data",
            data: files
        }).done(function (result) {

            $("#result").html(result);

        });
</script>

if you can, fix my code or give me new code i want to see your suggestions for doing this.

Edit code from comment:

[HttpPost] 
public ActionResult GetCount(HttpPostedFileBase file) 
{ 
  using (StreamReader reader = new StreamReader(file.FileName)) 
  { 
    string result = reader.ReadToEnd(); 
    return PartialView(result.Count()); 
  } 
}

CodePudding user response:

You can try to use FormData to pass files to action with ajax.Here is a working demo:

view:

<form id="MyForm" method="post">
    <input id="fileInput" type="file" />
    <input type="submit" value="submit"/>
</form>
<script>
        $("#MyForm").submit(function (event) {
            event.preventDefault();
            var formData = new FormData();
            formData.append('file', $('#fileInput').get(0).files[0]);
            $.ajax({
                type: "Post",
                url: "/Counter/GetCount",
                data: formData,
                processData: false,
                contentType: false,
            }).done(function (result) {

                $("#result").html(result);

            });
        })
    </script>

Action:

[HttpPost] 
public ActionResult GetCount(IFormFile file) 
{ 
  using (StreamReader reader = new StreamReader(file.FileName)) 
  { 
    string result = reader.ReadToEnd(); 
    return PartialView(result.Count()); 
  } 
}

Result: enter image description here

CodePudding user response:

You can try to replace ajax request code with:

$.ajax({
  url: "/Counter/GetCount",
  data:files,
  type:'POST',
  contentType: false,
  processData: false,
  success: function(result){
    $("#result").html(result);
  }
});
  • Related