4

I am trying to post a form that has an input text field and also a file upload control using jquery ajax. However, I keep getting a 404 not found error. Below, I have included only the relevant part of razor code for brevity:

Here is a sample of the razor code:

<form id="uploadForm" asp-action="FileUpload" asp-controller="Content" method="post" enctype="multipart/form-data">
        <input asp-for="Title" class="form-control" required />
        <input asp-for="UploadFormFile">
        <button type="button" id="uploadButton" class="btn btn-primary" >Upload</button>
</form>

Javascript:

$(document).ready(function () {
    $("#uploadButton").click(function (e) {

        var data = new FormData($("uploadForm").serialize());
        var uploadedFile = $("#UploadFormFile").get(0).files[0];
        data.append(uploadedFile.name, uploadedFile);

        $.ajax({                
            url: '@Url.Action("FileUpload", "Content")',
            type: "POST",
            data: data,
            contentType: false,
            dataType: false,
            processData: false,
            success: function (result) {
                alert(result);
            }
        });
    });
});

Controller action:

    [HttpPost]
    public async Task<IActionResult> FileUpload()
    {
        CancellationToken cancellationToken = default(CancellationToken);
        long size = 0;
        var files = Request.Form.Files;

        foreach (var file in files)
        {
            var filename = ContentDispositionHeaderValue
                            .Parse(file.ContentDisposition)
                            .FileName
                            .Trim('"');
            filename = $@"\{filename}";
            size += file.Length;

            using (var fileStream = new FileStream(filename, FileMode.Create))
            {
                ...
            }
        }

        string message = $"{files.Count} file(s)/{ size} bytes uploaded successfully!";
        return Json(message);
    }

I tried using the answer here, but I still get a 404

The only time I did not get a 404 was when I changed the FormData to the below and did not append the uploaded file:

var data = new FormData($("uploadForm")[0]);

However, in this case, the controller action does not receive any data and the request.form was null.

So, is it possible to submit form data along with a file using jquery ajax in asp.net mvc core rc2?

Thanks.

Community
  • 1
  • 1
Girish
  • 758
  • 2
  • 8
  • 18
  • FYI a `FormData` object does not accept a string, only a `form` DOMElement, and your id selector is missing a `#`. Change the line which defines `data` to this: `var data = new FormData($("#uploadForm").get(0))`. As for the 404 error, check your routing. – Rory McCrossan Jun 11 '16 at 09:35
  • `var data = new FormData($("#uploadForm")[0]);` is all you need (you were missing the `#`) and that will include all form controls including the file input –  Jun 11 '16 at 09:36
  • @StephenMuecke, your code worked perfect. I was also trying to upload a large file and IIS was not allowing it due to maxRequestLength not being set to a higher value. Anyway, if you can post your line of code as an answer, I will mark it as the accepted answer. Thanks. – Girish Jun 11 '16 at 12:55
  • I'll mark it as a dupe instead :) –  Jun 11 '16 at 12:58

1 Answers1

1

use like this

var formData = new FormData();
var uploadedFile = document.getElementById("UploadFormFile").files[0];
formData.append(uploadedFile.name, uploadedFile);
var xhr = new XMLHttpRequest();
xhr.open("POST", '@Url.Action("FileUpload", "Content")', true);
xhr.send(formData);

Hope this will help you

Ansh Takalkar
  • 119
  • 1
  • 9