0

Important note: I'm getting suggestions to follow this link to be able to resolve my issue. But, I'm already doing whatever has been suggested in this post.

I'm following this article and trying to upload Image file to server using jQuery AJAX. I'm trying to find a way to get all the details inside UploadFileUsingJQueryAJAX action method of HomeController under the emp parameter

Below is the code in HomeController:

    public IActionResult UploadFileUsingJQueryAJAX()
    {
        return View();
    }

    [HttpPost]
    public IActionResult UploadFileUsingJQueryAJAX(Employee emp)
    {
        return View();
    }

Below is the code in UploadFileUsingJQueryAJAX view

@{
    ViewData["Title"] = "Upload File Using jQuery AJAX";
}
<h1>@ViewData["Title"]</h1>
<form id="myForm" method="post" enctype="multipart/form-data" asp-action="UploadFileUsingJQueryAJAX" asp-controller="Home">
    <table>
        <tr>
            <td>First name:</td>
            <td><input type="text" id="txtFirstName" name="txtFirstName" /></td>
        </tr>
        <tr>
            <td>Last name:</td>
            <td><input type="text" id="txtLastName" name="txtLastName" /></td>
        </tr>
        <tr>
            <td>Photo:</td>
            <td><input type="file" id="photo" name="postedFile" /></td>
        </tr>
        <tr>
            <td>Photo:</td>
            <td><input type="button" value="Submit" onclick="AjaxFormSubmit();" /></td>
        </tr>
    </table>
</form>
@section Scripts {
    <script src="~/js/upload_file_using_jquery_ajax_script.js"></script>
}

Below is the Employee class which is inside Models folder.

public class Employee
{
    public int EmpId { get; set; }
    public string FistName { get; set; }
    public string LastName { get; set; }
    public IFormFile Photo { get; set; }
}

Below is the required javascript inside upload_file_using_jquery_ajax_script.js

function AjaxFormSubmit() {
    var url = $('#myForm').attr('action');
    var firstName = $('#txtFirstName').val();
    var lastName = $('#txtLastName').val();
    var photo = $('#photo')[0].files[0];

    var model = {
        url: url,
        FirstName: firstName,
        LastName: lastName,
        Photo: photo
    };

    SubmitForm(firstName, lastName, photo);
}

function SubmitForm(firstName, lastName, photo) {
    $.ajax({
        type: 'POST',
        url: '/Home/UploadFileUsingJQueryAJAX',
        data: {
            FirstName: firstName,
            LastName: lastName,
            Photo: photo
        },
        dataType: 'json',
        cache: false,
        beforeSend: function (xhr) {
            xhr.setRequestHeader("XSRF-TOKEN",
                $('input:hidden[name="__RequestVerificationToken"]').val());
        },
        success: function (response) {
            console.log(response.responseText);
            if (response.status == "success") {
                //alert("File : " + response.filename + " is uploaded successfully");
                console.log(response.responseText);
            }
        },
        error: function (err) {
            alert("Error occurs" + err.responseText);
        }
    });
}

I'm getting below error in Browser's console window when executing the program.

enter image description here

Values were not passed to controller action method. After some modifications, looks like something went wrong. The Controller action method is not even hitting.

After some analysis, found this article and changed the code accordingly. But, no luck.

Tried to resolve the issue by following some web resources like this, this, and this but no luck.

Can someone help me to resolve the issue! Actually, as per the requirement I have to upload and read Excel file. But I'm trying in this program to upload Image file as I'm getting almost all the articles on uploading images only and I want to align with the article while learning and understanding the concept. Please let me know if I need to follow some addtional steps that I need to follow if I need to upload and read Excel file from Controller action method.

Ashok kumar
  • 1,593
  • 4
  • 33
  • 68
  • Does this answer your question? [jQuery Post blob object gives Uncaught TypeError: Illegal invocation](https://stackoverflow.com/questions/35872448/jquery-post-blob-object-gives-uncaught-typeerror-illegal-invocation) – Natrium Jan 02 '23 at 07:32
  • 1
    Hi @Natrium: Already verified this post before I posted this question in stackoverflow. There's nothing to takeout from this post for my issue. – Ashok kumar Jan 02 '23 at 10:44
  • _"I'm already doing whatever has been suggested in this post."_... no you're not. Where's your `FormData` instance? – Phil Jan 03 '23 at 03:35

1 Answers1

2

You need to use FormData to upload file in ajax and add configurations like:

processData: false,
contentType: false,

Please refer to this code:

function AjaxFormSubmit() {
        var url = $('#myForm').attr('action');
        var firstName = $('#txtFirstName').val();
        var lastName = $('#txtLastName').val();
        var formData = new FormData()
        formData.append("FirstName",firstName);
        formData.append("LastName", lastName);
        formData.append("Photo", $('#photo')[0].files[0]);

        SubmitForm(formData);
    }

    function SubmitForm(FormData) {
        $.ajax({
            type: 'POST',
            url: '/Home/UploadFileUsingJQueryAJAX',
            data: FormData,
            dataType: 'json',
            cache: false,
            processData: false,
            contentType: false,
            beforeSend: function (xhr) {
                xhr.setRequestHeader("XSRF-TOKEN",
                    $('input:hidden[name="__RequestVerificationToken"]').val());
            },
            success: function (response) {
                console.log(response.responseText);
                if (response.status == "success") {
                    //alert("File : " + response.filename + " is uploaded successfully");
                    console.log(response.responseText);
                }
            },
            error: function (err) {
                alert("Error occurs" + err.responseText);
            }
        });
    }

Demo:

enter image description here

BTW: you wrote FirstName as FistName in Employee.

Xinran Shen
  • 8,416
  • 2
  • 3
  • 12