Sending a File Object and Data to an MVC 6 Controller in ASP.NET 5 using JavaScript

I have been working with an Ajax function that is supposed to handle file upload, but I am encountering some issues. Despite dragging and dropping the file, nothing seems to happen with the Ajax. Upon inspecting the properties on the page, I can see that the file exists in my JavaScript function, but it doesn't get sent to the controller. The Index Controller does not receive any file properties in the parameters when I debug it. Moreover, the Ajax does not display any success or failure alert messages.

My ultimate goal is to extract and parse the data from the uploaded file.

JavaScript

function sendFile(file) {


    $.ajax({
        type: "POST",
        url: "HomeController/Index", // the method we are calling
        contentType: "application/json; charset=utf-8",
        data: { filename: file.name, fileType: file.type, fileSize: file.size },
        dataType: "json",
        success: function(result) {
            alert('Yay! It worked!');
            // Or if you are returning something
            alert('I returned... ' + result.WhateverIsReturning);
        },
        error: function(result) {
            alert('Oh no :(');
        }
    });

    Output(
        "<p>File information: <strong>" + file.name +
        "</strong> type: <strong>" + file.type +
        "</strong> size: <strong>" + file.size +
        "</strong> bytes</p>"
    );

}

AJAX

$.ajax({
    type: "POST",
    url: "HomeController/Index", // the method we are calling
    contentType: "application/json; charset=utf-8",
    data: { filename: file.name, fileType: file.type, fileSize: file.size },
    dataType: "json",
    success: function(result) {
        alert('Yay! It worked!');
        // Or if you are returning something
        alert('I returned... ' + result.WhateverIsReturning);
    },
    error: function(result) {
        alert('Oh no :(');
    }
});

C#

public IActionResult Index(string fileName, string fileType, int fileSize)
{
    ViewBag.Environments = _configHelper.GetEnvironments();
    var model = new HomeViewModel { Environment = "DEV" };
    return View(model);
}

CSHTML

<div class="form-group col-md-12">
    <label>Company Ids:</label>
    <div id="filedrag"><textarea class="form-control" rows="5" id="textAreaCompanyIDs" placeholder="Drop Files Here"></textarea>
    </div>
</div>

Answer №1

In order to access the file within the controller, you must ensure that the complete file is being sent.

Consider implementing the following:

AJAX Request:

 $.ajax({
            type: "POST",
            url: "HomeController/Index", // specify the method to call
            contentType: "application/json; charset=utf-8",
            data: { file: file, fileType: file.type, fileSize: file.size },
            dataType: "json",
            success: function(result) {
                alert('Success! The operation was completed.');
                // Handle the result data here
                alert('Returned data: ' + result.SomeData);
            },
            error: function(result) {
                alert('Oops, something went wrong :(');
            }
        });

Controller Implementation:

   public IActionResult Index(HttpPostedFileBase file, string fileType, int fileSize)
    {
        ViewBag.Environments = _configHelper.GetEnvironments();
        var model = new HomeViewModel { Environment = "DEV" };
        return View(model);
    }

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

What is the best method to extract text data from the Froala editor?

Currently, my method involves using $('div#edit').froalaEditor('html.get') to get the HTML data from the editor. Unfortunately, this process becomes problematic when trying to process or store the text data in my backend due to the pres ...

Using Ajax to Receive Data in a Separate JavaScript Function

I have a scenario where I am making an AJAX call in one function and attempting to capture the result in another function. Let me explain this in detail below: function myMain(){ var test = myWPackage(); alert(test); } function myWPackage(){ ...

Verify if the item already exists in the Vue.js array

Here is the data I have: data: function() { return { conversations: [ ] } } I am retrieving my data from the response object using response.data.conversation Is there a method to verify if this.conve ...

What is the best way to display a unique image in a div based on the size of the

Being new to web design, I have a question about creating a webpage with a large image in the center like on GitHub's Windows page. How can I work with the image inside that particular div or area based on different screen sizes? Is it possible to mak ...

Ensure that the array in Jest does not have any falsy values present

Attempting to utilize Jest for a unit test to ensure the absence of falsy values in my array named values. Unfortunately, the initial approach is not effective; the test actually passes: const badValues = ['', null, undefined, false, {}, []]; e ...

Is it possible to use Node.js without resorting to template engines

Recently, I embarked on a journey to explore the world of backend development, focusing my attention on Node.js. As I delved into Express.js and familiarized myself with routing, a curious thought crossed my mind. Is there a method to transmit data direc ...

Discover the technique for splitting a string using jQuery with multiple strings as separators

I am looking to split a string in jQuery or JavaScript using multiple separators. When we have one string as a separator, our code looks like this: var x = "Name: John Doe\nAge: 30\nBirth Date: 12/12/1981"; var pieces = x.split("\n"), p ...

Show the error message from passport.js authentication in the user interface

I am currently working on a new project with Sails.js and using Passport.js for user authentication. Despite having the basic authentication set up, I am struggling to display error messages in the login view when incorrect credentials are entered. I have ...

"Transforming a query into a JSON array - a step-by-step

My query generates the following output: { key:1,label:"R. Bulan"} { key:2,label:"R. Bintang"} { key:3,label:"R. Akasia"} { key:4,label:"R. Guest Room"} This is my SQL query: select '{ '||'key:'||IDMEETINGROOM||''||',l ...

Is there a way to deactivate the toggle button in my code?

<label class="switch switch-yes-no" id="disable_'+id+'" style="margin: 0;font-weight: bold;"> <input class="switch-input" type="checkbox" id="disable_'+id+'" /> <span class="switch-label" data-on="Enabled" data-off="Disab ...

What could be causing Express to display a different page than the one specified in res.render?

Upon trying to view the compare.ejs page, I encountered an unexpected issue where a different page was being rendered instead. What could be causing this discrepancy? Here is my app.js code: var compare = require('./routes/compare')(nav); app.u ...

How can I add a hyperlink to a Javascript string array?

I am currently facing a challenge in adding a hyperlink to a string using .link and .innerHTML methods. I believe there might be a misunderstanding on my part as I am quite new to this. Here is the code snippet I have been working with: <div id="type ...

Simplify an array in Javascript

I have a collection of objects structured in the following way: let list = [ { 'items': [ 'item 1', 'item 2' ] }, { 'items': [ 'item 3' ] } ] My goal is to flatte ...

Saving text to the clipboard with the click of an ASP.NET button

Looking for assistance on how to copy text into clipboard upon a button click in asp.net. The goal is to have the text copied directly to the client's clipboard when the button is clicked. Appreciate any help, AnkiReddy ...

Using the npm package in JavaScript results in a return value of 1

Recently, I have been working on turning this into an npm package: Test.tsx: import React from "react"; export default class Test extends React.Component { public render() { return ( <h1> Hallo & ...

Exploring ways to retrieve a video thumbnail with VueJS3

I am currently working on a project to create a simple program that retrieves movies from my AWS-S3 bucket and transforms them into picture thumbnails. Below is the code I have written: <template> <img :src="imgURL" class="card- ...

I have chosen to utilize the .Net FW package over .Net Standard within my .Net Core 2.0 project, leading to a warning with code NU1701

In my .Net Core 1.0 project, I successfully utilized the nuget package sqlite-net-pcl without any issues. The package was in its .Net Standard 1.1 version. However, upon upgrading to .Net Core 2.0, I encountered some build warnings: 1>C:\Projects& ...

Setting up VideoJS Flash backup

Due to Firefox's restriction on using an .mp4 file in the <video> tag, I am required to utilize the Flash fallback option on my VideoJS player. When it comes to Chrome, Safari, and IE, I can customize my VideoJS player via JavaScript to perform ...

What is the best way to divide React Router into separate files?

My routes configuration is becoming cluttered, so I have decided to split them into separate files for better organization. The issue I am facing is that when using 2 separate files, the routes from the file included first are rendered, but the ones from ...

Switch up the Yii ListBox default onChange event to utilize AJAX with onClick instead

Below is the code I have for a <select> element: $htmlOptions = array( 'size' => '20', 'ajax' => array( 'type' => 'POST', 'url' => Y ...