Controller Not Deserializing Ajax File Upload in MVC 5

There seems to be an issue with deserializing the data sent using the multipart/form-data type within an MVC 5 project. Despite appearing valid in Fiddler, the data is not being mapped into the controller method. While debugging, it is evident that all parameters are null.

The form sends one hidden text field and up to two files to the controller. Below is the method signature:

[HttpPost]
public async Task<ActionResult> UploadFile(string id, FormCollection form, IEnumerable<HttpPostedFileBase> files)

The implementation of the method is irrelevant as the problem lies in the parameters not being populated.

Here is a redacted version of the Fiddler output:

POST http://localhost:52876/Projects/UploadFile/5550cdc52300560f6c7b36eb HTTP/1.1
Host: localhost:52876
Connection: keep-alive
Content-Length: 90889
Authorization: Negotiate oXcwdaADCgEBoloEWE5UTE1TU1AAAwAAAAAAAABYAAAAAAAAAFgAAAAAAAAAWAAAAAAAAABYAAAAAAAAAFgAAAAAAAAAWAAAABXCiOIGAbEdAAAADwAbnJriMKEzkS3OifgoahejEgQQAQAAAPUXp1AtIpqEAAAAAA==
Accept: */*
Origin: http://localhost:52876
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.152 Safari/537.36
Content-Type: multipart/form-data
DNT: 1
Referer: http://localhost:52876/Projects/ProjectSetupForm/5550cdc52300560f6c7b36eb
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8
Cookie: donotshowgettingstarted=%7B%22state%22%3Atrue%7D; __RequestVerificationToken=UnL5s7w5OYKgywE5L8jqwbH8PulgF0BG0Ne_qZV5QMOj7pWdXw6qzN1pRYqc4rwKYiWveltrBs1SmJe2o7ndXufkOJFrC1wHOoK2zAXdnQw1

------WebKitFormBoundaryB3sb0uQDOIiNQXCD
Content-Disposition: form-data; name="__RequestVerificationToken"

  f25ipWgwweX4S9Y6aEnQdxGCsvr7D3RznTui8_b5paCT1uTV8UNG0d6zJDXKUWYPHISOKmgD24KH206x_PGQ3KpXlG9YgOL-qqJ8v7DPETVfGk2PvsFm2aKuAS3xAYZI0
------WebKitFormBoundaryB3sb0uQDOIiNQXCD
Content-Disposition: form-data; name="files"; filename="MyIcon.bmp"
Content-Type: image/bmp

[REDACTED FILE CONTENTS]

------WebKitFormBoundaryB3sb0uQDOIiNQXCD
Content-Disposition: form-data; name="files"; filename=""
Content-Type: application/octet-stream


------WebKitFormBoundaryB3sb0uQDOIiNQXCD
Content-Disposition: form-data; name="type"

output
------WebKitFormBoundaryB3sb0uQDOIiNQXCD--

The debugging data shows only one file being sent and a blank file field. The same results occur when both fields are populated.

Below is the JavaScript method handling the form onSubmit event:

$('#attachment-upload form').submit(function (e) {
    e.preventDefault();

    $('#attachment-upload').removeClass('fade').modal('hide');
    $('#attachment-progress').modal('show').addClass('fade');

    $.ajax({
        xhr: function () {
            var xhr = new window.XMLHttpRequest();

            xhr.upload.addEventListener('progress', function (event) {
                if (event.lengthComputable) {
                    var percent = (event.loaded / event.total) * 100;
                    $('#attachment-progress div.modal-body .progress-bar').width(percent);
                    $('#attachment-progress div.modal-body .progress-bar').attr('aria-valuenow', percent);
                    $('#attachment-progress div.modal-body .progress-bar span').html(percent);
                }
            }, false);

            return xhr;
        },

        url: this.action,
        type: 'POST',
        contentType: "multipart/form-data",
        processData: false,
        data: new FormData(this),
        success: function (data) {
            //my success function here
        },
        error: function (jqxhr, status, error) {
            $('#upload-progress-section').addClass('hidden');
            $('#upload-complete-section').removeClass('hidden');

            $('#attachment-progress div.modal-header h1').html("Upload Error");
            $('#upload-complete-section p').html("Upload has failed: " + status + " - " + error);
            $('#attachment-progress div.modal-footer button').removeAttr('disabled');
        }
    });
});

Based on the Fiddler output, it seems like there might be an issue with the controller method signature, causing parameter binding failure. It is surprising that even the FormCollection parameter is null.

Are there any known issues with using multipart/form-data to upload files via ajax, or could there be a mistake in the implementation?

Answer №1

Kudos to @DarinDimitrov for alerting us to the problem - turns out that the multipart/form-data content type needs a specific boundary.

By not specifying the contentType as multipart/form-data and instead using $.ajax with contentType: false, the ajax function was able to add the correct boundary automatically. This allowed the controller to properly deserialize the data without any issues.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The back button stops functioning properly following a push state operation

When the user clicks the back button, there is an issue with the page reloading. Ideally, the previous page should be displayed but instead, the same content keeps appearing. [url removed] ...

Efficient page navigation bar that doesn't clutter the layout

I'm facing an issue with my navbar setup. I want it to stay at the top of the page without being sticky. However, the presence of the navbar is causing a scroll to appear on my page. This happens because: The navbar takes up space I sometimes use tri ...

Tips on how to automatically resize the browser window to a specific width and height once it has been minimized

If a JSP page is minimized onload, we need to find a way to restore it through a JavaScript call. Are there any other methods available for achieving this? The restoration should be to the height and width selected by the user. I have attempted the followi ...

Troubleshooting jQuery: Unable to refresh the webpage

I have a PHP page that contains a form, checkboxes, and a submit button. I added an if statement to execute a PHP script I created when the button is clicked, which deletes certain values from the selected rows. The button functions properly and changes s ...

The menu is about to receive some custom styling

I have come across a webpage where I need to make some modifications, but I am unable to locate the script responsible for applying the inline style. This issue only seems to be occurring on the mobile version with the dropdown menu. <div class="is-dri ...

Having difficulty establishing a connection between my node.js application and the database

I've been struggling to establish a connection between my application and the database. Despite attempting the code below, my models are still not being recognized. const MongoClient = require('mongodb').MongoClient; const assert = require(& ...

Retrieve the corresponding value from an object received from express and display it on a jade template

I'm currently working on a solution to display the correct user information on a page when users navigate to "/users/:name". For example, I want to show "welcome user2" if user2 is logged in. My approach involves passing along the parameter from "/use ...

Images cascading like a downpour on a canvas (Javascript)

I have been experimenting with canvas, attempting to create a simulation of random falling objects. I've successfully drawn the background image, but I'm having trouble with the second image that is supposed to simulate a rain drop. I've ma ...

Perform a bash command using PHP when an HTML button is clicked

Today, my brain seems to be on vacation. Currently, I have set up a Raspberry Pi with vlc running and connected to a mounted screen on the wall. There is a web page with simple controls to manage the pi, switch between different vlc streams, or stop stream ...

What is the best way to enhance a tool-tip with images or legends?

Currently, I have implemented a tool-tip feature which works for a text box. However, the issue is that users are unaware of the presence of the tool-tip for the text box until they hover over it. My question is, how can I make it more obvious to users t ...

Trigger a Redux action with the following action as the payload in order to display a Material UI snackbar or dialog

Currently, my project involves using React along with Redux and Material UI to develop a web application. The web app consists of numerous pages and components. It is common practice to have a snackbar or dialog interact directly with the user's actio ...

What steps can I take to resolve the spawn unknown error when using npx create-next-app in Visual Studio Code (VSCode)?

Every time I attempt to create a new app using either vscode or cmd, I encounter a spawn unknown error. The error message says "Aborting installation. Unexpected error. Please report it as a bug: Error: spawn UNKNOWN". Unfortunately, the installation abo ...

Combine Immer and NgRx reducer for improved state management

Upon analyzing redux and ngrx, it appears that immer is the preferred library for creating a copy of the state before storing it. In following the example provided by immer, I implemented the following code in my reducer: on(exampleActions.updateExample ...

Displaying form after Ajax submission

I have implemented an AJAX code to submit my form, but I am facing an issue where the form disappears after submission. Here is my current code: <script> $('#reg-form').submit(function(e){ e.preventDefault(); // Prevent Default Submissi ...

Coding two for loops in React Js to generate a 3X3 grid for a tic-tac-toe game

I am currently learning React Js through the official tutorial where we are building a tic-tac-toe game. To create the square boxes in the game board, initially I hard-coded all the squares like this: render(){ return ( <div> <div cla ...

Is it possible to generate a JSON file from a flowchart with the help of d3.js?

Situation: I'm currently in the process of developing a tool that will enable us to generate flow charts and then export the data into a JSON file for use in other services. Being new to JavaScript, I've come across d3 quite often. Can d3 handle ...

[Vue alert]: Component mounting failed due to usage of mixin with a parameter

For the past day, I've been facing difficulties creating a Vue mixin with a parameter. When attempting to do so, I encounter a [Vue warn]: Failed to mount component: template or render function not defined error. Below is my JS file which includes the ...

Communication between Angular Controller and Nodejs Server for Data Exchange

Expanding on the solution provided in this thread, my goal is to implement a way to retrieve a response from the node server. Angular Controller $scope.loginUser = function() { $scope.statusMsg = 'Sending data to server...'; $http({ ...

Is it possible to use JavaScript for detecting third-party videos?

I'm currently developing an HTML5 video player that also has a fallback to flash. One of the challenges I am facing is that the video content is being provided by various third-party sources. It seems that some of these third parties serve videos bas ...

Print on the Console in a Vintage-Inspired Way

When it comes to writing on the Console, I need to display the message "Enter your User Name:" in a unique way. I've been using Console.WriteLine("Enter your..."); but I want the prompt to appear as if it's being typed, similar to how it's d ...