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

Transform the angular code in order to execute innerHTML functions

function campform() { $.ajax({url: "{{ path('campform') }}", success: function(result){ $("#respuesta").html(result); }}); } I am having trouble with the angular code in the result I received. Can anyone provide guidance on how t ...

Discovering the correct element and typing for an HTML attribute through JavaScript

We are currently working on test automation and I am looking for a way to identify the Element and Type associated with it within an html (Data-qa) attribute. For example, when looping through, the Element is identified as input and the type is radio. < ...

Tips for utilizing multiple ngFor directives for property binding within a single directive

After implementing the ng-drag and drop npm module with the draggable directive, I encountered an issue while trying to display a list of items from a 2D array using li elements. Since multiple ngFor's are not allowed in Angular, I needed to come up w ...

What is the best way to eliminate the unnecessary space that appears by default in the Ajax control toolkit tab panel control

When using the Ajax Control Toolkit tab panel, you may notice that there is automatic spacing added around all four corners of the body. For instance, when viewing the TabPanel on the page http://www.asp.net/ajax/ajaxcontroltoolkit/Samples/Tabs/Tabs.aspx ...

How to access a webpage on your Android device without the address bar visible

My question relates to sending Push Notifications through OneSignal. Upon clicking a push notification, it automatically redirects the user to my website. Is there a way to hide the address bar on the browser when this happens? I attempted using the follo ...

Leverage AJAX on the client-side for optimal performance while utilizing node.js

I am currently working on a simple nodejs application that displays HTML pages. Within this application, there are two buttons that are linked to JavaScript functions in separate files. One of the functions uses ajax, while the other does not. However, I a ...

Ways to efficiently handle numerous asynchronous requests in a NodeJS/Express API

I am looking to consolidate a variety of REST APIs into a single, easy-to-use API. My plan is to develop a straightforward nodejs/express API that will handle the individual calls asynchronously and then aggregate all the results together at once. The Jav ...

Deciphering HTML elements using JSON within the Angular framework

Upon receiving JSON data from my server, the reviews array is typically filled with numerous reviews. However, for demonstration purposes, I am presenting only one review here. { "reviews": [ "<br>We have found 20 reviews on external web ...

Unable to execute a JavaScript function when triggered from an HTML form

This is the code for a text conversion tool in HTML: <html> <head> <title> Text Conversion Tool </title> <script type="text/javascript"> function testResults(form) { var str = form.stringn.value; var strArray = str.split(" ...

Is it feasible to directly load image objects into jQuery colorbox?

Currently, I am working with the "colorbox" jQuery plugin and I have a specific requirement to dynamically load a set of preloaded image objects into colorbox. The challenge lies in the fact that I have three different image sizes - thumbnail, display, an ...

Use ajax, javascript, and php to insert information into a database

Issue at Hand: I am trying to extract the subject name from the admin and store it in the database. Following that, I aim to display the query result on the same webpage without refreshing it using Ajax. However, the current code is yielding incorrect outp ...

Strange error message regarding ES6 promises that is difficult to interpret

Snippet getToken(authCode: string): Promise<Token> { return fetch(tokenUrl, { method: "POST" }).then(res => res.json()).then(json => { if (json["error"]) { return Promise.reject(json); } return new Token ...

Storing data locally and replacing the current URL with window.location.href

My course mate and I are working on writing a code that saves an order to local storage and redirects to an order page when the order button is clicked. However, we are facing issues where clicking on the order button doesn't register in the applicat ...

Exploring the nuances of receiving responses with NextJs, Nodemailer, and Fetch

Currently in the process of constructing a basic contact form with Next.js, nodemailer, and fetch. Despite successfully sending emails from the frontend form to the designated email account, the network shows the contact submission as pending. After approx ...

Getting variables from different functions in Python can be achieved by using the return

I am trying to implement a feature where I can fetch a search term from the function getRandomVideo() and then use it in a jQuery statement. For example, if I get "Beethoven" as the search term from the variable searches, I want to use it to retrieve JS ...

JavaScript throws an error when attempting to access an object's methods and attributes

Within my Angular.js module, I have defined an object like this: $scope.Stack = function () { this.top = null; this.size = 0; }; However, when I try to use the push method of this object, I encounter an error stating undefined: ...

The sorting function in Vue.js, _.orderBy, seems to be having trouble sorting

UPDATE This is the json data retrieved through an API using axios. bannerData= [ { "id": 118, "title": "Geruchsbel\u00e4stigung", "location": "DOR", "pressInformation": [ { ...

Guide on transferring the "req" object to the client side

I am curious to explore the possibility of displaying the entire content of the req object on the client side. const express = require('express'); const app = express(); app.get('/', (req, res) => { // sending req object to th ...

Scroll the content of a div to the bottom using JavaScript

I'm facing a situation with my code: function scrollme(){ dh=document.body.scrollHeight ch=document.body.clientHeight if(dh>ch){ moveme=dh-ch window.scrollTo(0,moveme) } } However, I am looking for a way to make it scroll only within a specific d ...

Utilizing headless Chrome to automatically capture AJAX requests

Chrome officially supports running the browser in headless mode, allowing for programmatic control through the Puppeteer API and/or the CRI library. I've thoroughly explored the documentation but have not discovered a method to programmatically captu ...