Transmit a JavaScript object containing both data and a file to an ASP.NET Core server

When I try to send data along with a file in a javascript object to asp.net core, the values arrive as null at the asp.net core method (List<Upload> listUpload).

I conducted a test by removing the File property from the javascript object, and then the null issue disappeared. It seems that the problem lies with the File property not mapping correctly with the model property called File of type IFormFile.

Below is the javascript code snippet:

jQuery('#tblDocuments > tbody > tr').each(function () {
   checkBox = jQuery(this).find('td').eq(0).children();
    
   inputFile = jQuery(this).find('td').eq(2).children()[0].files[0]; 

    let Upload = {
        File: inputFile,
        CodigoVendaArquivo: res,
        CodigoClienteArquivo: cliente,
        Checkbox: checkBox[0].id
    };
    listUpload.push(Upload);
});

I'm attempting to send the data using fetch:

fetch('../../upload', {
    method: 'POST',
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    },
    body: JSON.stringify(listUpload)
}).then(res => res.json())
.then(res => {

    if (res == 1) {
     // success
    }

});

Now, here's my asp.net core method:

[Route("upload")]
[HttpPost]
public JsonResult Upload([FromBody] List<Upload> listUpload)
{
    // something
}

And below you can find my Model:

public class Upload
{
    public IFormFile File { get; set; }
    public string CodigoVendaArquivo { get; set; }
    public string CodigoClienteArquivo { get; set; }
    public string Checkbox { get; set; }
}

Answer №1

It is best to avoid nesting an IFormFile within the Upload class. When dealing with scenarios like uploading an IList<Upload> where each item in the list has a property of IFormFile, there is a potential risk of encountering a bug that could lead to excessive memory consumption (I personally experienced a memory leak consuming about 6.7G until I resolved it). For more details, refer to

To address this issue, one solution recommended by WahidBitar on GitHub is to create a wrapper to handle the payload.


In regard to your specific query, refraining from embedding an IFormFile within the Upload class is advisable.

Here's a functional example :

formData, define a function getFormData() :

    function getFormData(listUpload){
        var formData = new FormData();
        function getFieldName(index,name){
            return "Uploads[" + index + "]." + name ;
        };
        function getFileName(index,name){
            return "Uploads[" + index + "].CodigoFile." + name ;
        };

        for(var i =0 ;i <listUpload.length; i++){
            var upload = listUpload[i];
            formData.append(getFieldName(i, 'CodigoVendaArquivo'), upload.CodigoVendaArquivo);
            formData.append(getFieldName(i, 'CodigoClienteArquivo'), upload.CodigoClienteArquivo);
            formData.append(getFieldName(i, 'Checkbox'),upload.Checkbox)
            formData.append(getFileName(i, 'File'), upload.File);
        }
        return formData;
    }

Subsequently, send the formData using the following approach:

    jQuery('#tblDocuments > tbody > tr').each(function () {
        ...
        listUpload.push(Upload);
    }

    var formData = getFormData(listUpload);
    fetch('../../upload', {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(listUpload),
        body:formData,
    })
    .then(res => res.json())
    .then(res => {
        if (res == 1) {
            // success
        }
    });

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

Encountering a configuration file issue while setting up a Sageframe website on IIS hosting

After downloading SageFrameV2.1, I attempted to host the site on my local IIS Server, but encountered an issue while trying to browse the site. HTTP Error 500.19 - Internal Server Error The requested page cannot be accessed because the related configurat ...

Allow Vue to handle the registration of the datepicker event

Is there a way to notify Vue when the datepicker changes the selected date? new Vue({ el: '#app', data: { termin: '' }, computed: { }, methods: { } }) This is just an input field: <div id="app"> <div c ...

Downloading Files Using Ajax and Javascript

When a client makes a request through XMLHttpRequest, the information is sent to the server. The server compiles a CSV file and sends it back as the output stream of the response to the client. Next, the client's browser should display a download dia ...

JavaScript form with checkboxes for user options followed by a text area for easy copying with the shortcut Ctrl + C

I was unable to find a thread similar to my question, but here is one that is somewhat related: How can I output multiple text fields to one page My goal is to allow for multiple user inputs (text, checkboxes, etc) and have them displayed in a simple text ...

Determine the HTTP status code for a request using Vue.js and Ajax

I need to retrieve the HTTP status code after submitting a form (using the form submission function): return fetch(serviceUrl + 'Collect', { method: "POST", headers: new Headers({ "Content-Type": "application/json", Authoriza ...

Navigating through sub-components in HTML code

After observing how others are able to set sub-object properties in markup, such as with Telerik's RadComboBox, I see that it is possible. For instance... <telerik:RadComboBox runat="server" ID="RadComboBox2"> <CollapseAnimation Duration ...

The Sinon stub appears to be completely ignored during the test, despite its successful use in earlier tests

I am currently testing the functionality of an express router using sinon. The first test in my code below passes without any issues, but I'm having trouble with the second test. It's not passing and I can't seem to figure out why. When I s ...

The push() function is triggering an error where db._checkNotDeleted is referenced incorrectly as a

I'm attempting to save an object in the database. Here's the code snippet I've been using: app.post('/newOrderWithObject', (req, res) => { var msg = {"name":"Harry"}; push(ref(db,"test/orders&qu ...

Verification of email address is not located in Clerk Auth, resulting in a 404 error message

For the past couple of days, I've been stuck on this issue and any help would be greatly appreciated. Thank you in advance! If necessary, I can provide additional code snippets. I am currently working on a project using nextjs with src. I'm try ...

Is it necessary to include `load` events if scripts are placed at the bottom of the body?

Is it necessary to enclose code in the following: window.addEventListener('load', () => {}) If your scripts are already loaded at the end of the body tag? Wouldn't this ensure that the DOM has been fully loaded, rendering a load event li ...

Determining the Existence of a User in MySQL Database Using C#

Although this question has been asked numerous times, I am looking to verify if a username is already in use within the database using c#. My attempt at achieving this was as follows: MySqlCommand cmd2 = new MySqlCommand("SELECT * FROM tablename WHERE ...

Implementing AngularJS table filters on user click

As a newcomer to angularjs, I am attempting to implement a filter on click. The user will select a source and destination, then click on the filter button. The table should display results based on the input. Upon page load, the table should already contai ...

Error: Next.js 13 does not support the use of localStorage

I encountered the following errors in my current Next.js 13 project and I am seeking assistance to resolve this issue. [1] - Error found in src\redux\store.js (line 12, character 15) @ localStorage [1] - Error: ReferenceError: localStorage is n ...

Error loading 'protobuf.js' while retrieving Firestore document

When trying to run a basic node file with Firebase and Firestore, the following code was used: const firebase = require("firebase"); const http = require('http') require("firebase/firestore"); firebase.initializeApp({ apiKey: '...' ...

Passing extra data along with dynamic routes in Reactjs

I'm currently working with Reactjs and Next.js, and I've got my [slug.js] functioning properly with the following URL: <Link href={`/${post.slug}`}><a> However, I need to pass a "hidden" additional parameter along with it. Whenever I ...

Newbie Inquiry: Text Input Field Randomly Losing Focus After Update in React

Having developed a component that displays checkboxes alongside text fields, my intention was for state to be updated upon clicking the checkboxes or typing in the fields. While the functionality of the text boxes seems fine, I encountered an issue where ...

AngularJS version 1.2.0 is experiencing an issue where the $http service is not properly sending requests

Why is AngularJS 1.2.0 $http not sending requests in $eval? Here is the code you can refer to: http://jsbin.com/oZUFeFI/3/watch?html,js,output ...

Ajax is able to fetch a JSON string, however it struggles to iterate through the successful data as an

My current project involves creating a graph using d3.js. I came across some php code that fits my needs perfectly. However, I am working with c# and Visual Studio, so I need to convert it into asp.net. For starters, I want to input some hardcoded sample d ...

Can 3D objects be easily moved by dragging and dropping in sap ui5?

Can a 3D object be generated in SAP UI5 allowing for interactive movement of objects? For example, creating a 3D model of a house where individual pieces like chairs can be manipulated. Is there a method to accomplish this task effectively? ...

Learning how to use the $t function in i18n translation files

Currently, I am utilizing Vue.js 3, Quasar 2, and vue-i18n for my translations. I have encountered an issue while trying to use $t or $tc in the translation file. The error message "$tc is not defined" keeps popping up. export default { survey: { n ...