Is there a way to send a JSON object and a file to an ASP.NET server using the fetch method?

I'm facing a challenge here, as I attempt to send a json object from my indexedDb along with an IFormFile object to the server at the same time. The method that handles this scenario is structured like so:

[HttpPost]
    public async Task<IActionResult> Create(BatchModel model, IFormFile vinFile)
    {
    //logic goes here
    }

Previously, this method was functioning well when I was submitting batchModels as regular JSON objects directly from the form using a POST request. However, since then, significant changes have occurred. Now, the client will upload it as soon as they reconnect online after being offline, using the following (simplified) approach:

if (infoChanged === true) {
    fetchPromises.push(
        fetch('/Batch/Create/', {
            headers: new Headers({
                'Content-Type': 'application/javascript' //Tried this with multi-part/form
            }),
            credentials: 'same-origin',
            method: 'POST',
            body: batch //, vinFile
        })
    );
}
return Promise.all(fetchPromises);

During testing, I attempted to utilize the method with only the model populated, and the only modification required in the C# code was adding a [FromBody] tag. However, now I need to ensure the vinFile is also filled. I experimented with using a FormData object, appending both the batch and vinFile with the same name as specified in the Create function. Unfortunately, this resulted in both variables being null.

Answer â„–1

The primary aspect to focus on is your header section. To switch your response to JSON, adjust the header as follows: { Content-Type: "application/json" }

It is essential to set up the format yourself.

fetch(myRequest).then(function(response) {
    var contentType = response.headers.get("content-type");
    if(contentType && contentType.includes("application/json")) {
      return response.json();
    }
    throw new TypeError("Sorry, we did not receive JSON data!");
  })
  .then(function(json) { /* continue processing your JSON data */ })
  .catch(function(error) { console.log(error); });

Explore more at Mozilla Developer Network regarding Fetch API usage

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

Grab all the text using Java Jsoup

I am having an issue with the code I have written. The doc.body.text() statement is not displaying the text content within the style and script tags. I examined the .text() function code and found that it searches for all instances of TextNode. Can someone ...

What is the process for retrieving external JSON using PHP with a content-type of text/plain?

I am attempting to retrieve an external JSON response using my PHP backend. However, I am encountering an issue where the external endpoint is returned with the Content-Type: text/plain;charset=utf-8, resulting in unreadable content. string 'ï¿½ï¿½ï¿ ...

Incorporate an onclick event to the elements within the array

I'm currently working on iterating over an array and adding an onclick event to each element. My goal is to be able to click on each div and have them log their values in the console. However, I am facing a challenge in applying the onclick event to e ...

I need to position a Vue component at the top of the page for a specific view only

How can I ensure that the component SiteHead only appears at the very top of the HomeView page, above the SiteNavigation component? If I place the SiteHead component within the HomeView.vue code, it ends up below SiteNavigation. Here is my App.vue code: & ...

Is there a way to extract tweet text from a json file for advanced analysis?

I have implemented a code snippet that utilizes the Twitter API to retrieve tweets based on a user-input search term and save them in a JSON file. My main focus is solely on extracting the actual tweet text and discarding any other information. Could you ...

exchanging a library for a different one

I'm faced with a relatively simple task here, but as I am just beginning to delve into object-oriented programming, it is proving to be quite perplexing for me. Currently, I am using the lon_lat_to_cartesian function from the following source: functi ...

When accessing a method exposed in Angular2 from an external application, the binding changes are lost

In my code, I have a method that is made public and accessible through the window object. This method interacts with a Component and updates a variable in the template. However, even after changing the value of the variable, the *ngIf() directive does not ...

Troubleshooting: Issues with Adding a New Row in Datatables using JQuery

CSS : <div class="datatable-header"> <button type="button" name="add" id="add" class="float-right btn btn-info">Add</button> </div> <div class="table-responsive"> <table ...

jQuery sidebar with a fixed position

Is there a way to implement a sidebar menu feature using jQuery that reappears on the left as the user scrolls down the page? You can see an example sidebar menu here. ...

The backend post request is returning only "undefined" in JavaScript

Hey there, I'm still learning JS so please bear with me. I've been working on incrementing a value in a JSON file within my JS backend app. However, whenever I try to increase the associated value by the key, it ends up creating a new section la ...

Is it possible for an object to be null even when its type is object

There's an issue that I can't seem to replicate. Personally, I'm not experiencing any errors but bugsnag reports that some users are encountering them. Take a look at snippet line 6 for more information. let lang = this.$store.state.lang ...

Re-calculating with Jquery when input is updated

I am looking for guidance on how to make the calculator recalculate based on a change in the #calcTotal input field. I have successfully calculated all fields and managed to update the #cwac field when one of the values before it changes. Here is the HTML ...

Oops! Looks like Laravel has hit its limit with 256 nesting levels in the function

I recently encountered a problem while working with an API that provides a mixture of JSON, STDClass, and Arrays. My main focus was extracting specific data from this nested structure which I managed to accomplish. However, the issue arose when I attempted ...

At what point does the chaining of async/await come to an end?

I was experimenting with node-fetch and encountered a question while using async / await: Do I need to make my function async if I use await in it? But then, since my function is async, I need to await it and make the parent function async. And so on... He ...

Pass a byte array from the back-end code to an AJAX request

I have a web method where I am converting HTML to PDF and saving it to a local folder. The goal is for the user to download the file without needing to reload the page. To achieve this, I am attempting to make an AJAX POST call to the web method to retriev ...

I came across a forum where someone mentioned encountering a similar issue but unfortunately, no solution was provided. Currently, I am working on setting up a reaction roles system but despite embedding the message, the role is not being

I am currently working on setting up a reaction roles system for my Discord server, but I have encountered a significant issue that may seem minor to most. The problem is that although my bot successfully sends embeds with corresponding emojis for the ro ...

What is the best way to refresh flexslider after it has been updated via AJAX?

At first, my slider is functional upon loading the page. However, after making an ajax call and receiving new slides to populate the slider, it becomes deactivated (as expected) https://i.sstatic.net/LC0yG.png Is there a method to reinitialize the flexsl ...

What is the best way to store an image file using html/angularjs?

I'm facing a challenge in my app where I need to save an image on one page and then retrieve it on another. So far, I have explored three different methods but none of them seem to be working for me: First, I attempted to use 'Parse.File' w ...

Changing the structure of a webpage in real-time and inserting new elements into the document

I have a custom x-template filled with a survey element (including a text field and radio button). Upon loading the screen, the database sends a JSON object to the UI based on previously stored sections. This JSON object is then used to populate the survey ...

What steps should be taken to avoid an event from occurring when an error message is encountered?

I have a dropdown list of cars where an error message is displayed if any of them becomes inactive. When the error message is shown, clicking on the Route Car button should prevent any event from occurring, i.e., no modal popup should be displayed. How ca ...