1

I have used kendo upload to upload files using Ajax Post in MVC core. I can call the API url but data is coming null. Have i passed data correctly? Here is my code.

<form id="uploadForm" action='@Url.Action("UploadFile", new { RmclientAccid = "1"  , AsAtDate = "testdate"})' method="post">
        @(Html.Kendo().Upload()
                        .HtmlAttributes(new { aria_label = "files" })
                        .Name("fileUpload")
        )
        <p style="padding-top: 1em; text-align: right">
            <button type="submit" class="k-button k-primary">Submit</button>
        </p>
    </form>

$(function () {
            $("#uploadForm").submit(function (e) {
                e.preventDefault();
                var upload = $("#fileUpload").data("kendoUpload"),
                    files = upload.getFiles(),
                    myFile = files[0];
                console.log(files);
                $.ajax({
                    type: 'POST',
                    url: '/RmReportTasks/UploadFile/',
                    dataType: 'json', 
                    processData: false,
                    contentType: false,
                    data: {
                        fileUpload: files[0].rawFile,
                        RmclientAccid: "1",
                        AsAtDate: "testdate"
                    },
                    success: function (data) {
                        console.log("succcess")
                    },
                    error: function (err) {
                        console.log("failure");
                    }
                });
            });
    });

Here is my controller.

 [HttpPost]
        public async Task<JsonResult> UploadFile(IEnumerable<IFormFile> fileUpload , string RmclientAccid, string AsAtDate)
        {
            var result = await _fileUploadManager.UploadDocument(fileUpload, RmclientAccid, AsAtDate);
            return Json(result);
        }

2 Answers 2

2

You can not send files directly using ajax to the server.

$(function () {
            $("#uploadForm").submit(function (e) {
                e.preventDefault();
                var formData = new FormData();
                var totalFiles = document.getElementById("uploadForm").files.length;
                for (var i = 0; i < totalFiles; i++) {
                   var file = document.getElementById("uploadForm").files[i];
                   formData.append("uploadForm", file);
                }
                $.ajax({
                    type: 'POST',
                    url: '/RmReportTasks/UploadFile/',
                    dataType: 'json', 
                    processData: false,
                    contentType: false,
                    data: formData,
                    success: function (data) {
                        console.log("succcess")
                    },
                    error: function (err) {
                        console.log("failure");
                    }
                });
            });
    });

And on the server-side, you can receive the file like this.

    [HttpPost]
    public void UploadFile()
    { 
       for (int i = 0; i < Request.Files.Count; i++)
            {
                var file = Request.Files[i];

                var fileName = Path.GetFileName(file.FileName);

                // Write logic to handle file here.
            }
   }
Sign up to request clarification or add additional context in comments.

1 Comment

If it helped and resolved your issue, you can accept the answer.
0

You can do it without form tag element.

Your CSHTML Code should be:

@(Html.Kendo().Upload()
  .Name("uploadFiles")
  .HtmlAttributes(new { aria_label = "files" })           
)

Your AJAX Call should be::

function OnBrowseSaveClick(e) 
{
  var uploadControl = $("#uploadFiles").data("kendoUpload"); //get a reference of the Upload
  var files = uploadControl.getFiles(); //Get the uploaded files
  var formData = new FormData();
  for (var i = 0; i < files.length; i++) { //loop through the files
    var file = files[i].rawFile;
    formData.append("uploadFiles", file); //append the property "rawFile" that holds the actual file in the FormData
  }
  $.ajax({
    url: '/Home/SaveFile',
    type: 'POST',
    data: formData,
    contentType: false, 
    processData: false, 
    success: function(result) {
      alert('Success');
    },
    error: function(result) {
      swal("Error :" + result.responseText);
    }
  });
}

Your Controller Action Should be:

public ActionResult SaveFile(IEnumerable<IFormFile> uploadFiles)
{
  // The Name of the Upload component is "uploadFiles" in the partial view.
  if (uploadFiles != null)
  {
    foreach (var file in uploadFiles)
    {
      var fileContent = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
        
      // Some browsers send file names with full path.
      // The sample is interested only in the file name.
      var fileName = Path.GetFileName(fileContent.FileName.ToString().Trim('"'));
      var physicalPath = Path.Combine(_webHostEnvironment.WebRootPath, "documents", fileName);
    
      using (var fileStream = new FileStream(physicalPath, FileMode.Create))
      {
        file.CopyTo(fileStream);
      }
    }
  }            
  // Return an empty string to signify success.
  return Content("");
}

Comments

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.