0

I am trying to upload a file, send it to the controller with ajax and save it in the database. Without Ajax, it is working perfectly, but when I submit the code with ajax in the controller I get a 0 result and cannot save the files into the DB.

Here is my code: View:

<form method="post" id="uploadForm" enctype="multipart/form-data" asp-action="UploadFile">
      
                <div class="k-content">
                    @(Html.Kendo().Upload()
                    .Name("files")
                    .Multiple(true)
                    .Messages(m=>m.Select("Select"))
                    .Validation(validation => validation
                    .AllowedExtensions(new string [] { ".doc", ".docx", ".pdf", ".txt"})
                    .MaxFileSize(5242880)
                    )
                    .HtmlAttributes(new { aria_label = "files"})

                    )
                    <p style="padding-top: 1em; text-align: right">
                        <button type="submit" id="uploadfile" class="btn btn-outline-primary rounded-pill">Upload</button>
                    </p>
                </div>
            </form>

The ajax call:

        $("#uploadfile").click(function (e) {
        e.preventDefault();

        var fileUpload = $("#addfile").data("kendoUpload"),
            files = fileUpload.getFiles();

        var filedata = new FormData();
        
        for (var i = 0; i < files.length; i++) {
            filedata.append(files[i].name, files[i]);
        }

        $.ajax({
            type: "POST",
            url: '@Url.Action("UploadFile")',
            contentType: false,
            processData: false,
            data: filedata,
            success: function (message) {
                alert(message);
            },
            error: function (xhr, status, error) {
                alert(error);
            },
        });

    });

And the controller, which works fine without ajax, but when data is submitted with Ajax, I get 0 result for the filedata

 [HttpPost]
    public async Task<IActionResult> UploadFile(IEnumerable<IFormFile> filedata)
    {
        foreach (var f in filedata)
        {
            if (f != null)
        {
            if (f.Length > 0)
            {
                var fileName = Path.GetFileName(f.FileName);
                var fileExtension = Path.GetExtension(fileName);

                var objfiles = new FileUpload
                {
                    FileName = fileName,
                    FileType = fileExtension,
                    FileSize = f.Length,
                    CretedOn = DateTime.UtcNow,
                };
                using (var target = new MemoryStream())
                {
                    f.CopyTo(target);
                    objfiles.FileData = target.ToArray();
                }
                _context.FileUploads.Add(objfiles);
            }
        }
            else
            {
                return Ok(false);
            }
        }
        await _context.SaveChangesAsync();
        return Ok(true);
   }
1
  • I hope the following blog will help you to upload the file using Ajax Jquery. The file will only be uploaded to the wwwroot folder. From there, you need to upload it to the database codemurals.blogspot.com/2020/08/… Commented Mar 2, 2021 at 6:13

2 Answers 2

1

You should use rawFile, as it holds the actual file data. And the key name should be corresponding to the receive parameter.

for (var i = 0; i < files.length; i++) {
    filedata.append("filedata", files[i].rawFile);
}
Sign up to request clarification or add additional context in comments.

Comments

0

the simple compelete solution for this is following

js code

 var fileupload = $("#FileUpload").get(0);
    var files = fileupload.files;
    var formData = new FormData();
    for (var i = 0; i < files.length; i++) {
        formData.append('files', files[i]);
    }

controller use IFormFile instead of IEnumerable

public IActionResult UploadFile(IFormFile files)
{
    **for storing in your project folder**
    string filePath = "";
    if (files != null) {
        string uploadsFolder = Path.Combine(_webHostEnvironment.WebRootPath, "uploads");
        filePath = Path.Combine(uploadsFolder, files.FileName);
        using(var fileStream = new FileStream(filePath, FileMode.Create))
            {
                files.CopyTo(fileStream);
    }
}

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.