Is it possible to upload a file using Angular and ASP.NET Web API Core?

I am encountering an issue with CORS policy while making requests. It works fine when the content-type is set to 'application/json'. However, when I try to upload a file using content-type 'multipart/form-data', I receive an error:

XMLHttpRequest cannot load http://localhost:20377/api/posts. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 500.

I am unsure why it works with application/json but not with multipart/form-data. Here's the code: Policy setup in Startup.cs

services.AddCors(options =>
{
    options.AddPolicy("CorsPolicy",
        builder => builder.AllowAnyOrigin()
        .AllowAnyMethod()
        .AllowAnyHeader()
        .AllowCredentials());
});

Angular method:

public createPost(title: string, body: string, file:File) {
    const token = this.authService.getToken();
    let formData: FormData = new FormData();
   
    formData.append('File', file, file.name);
    formData.append('Title', title);
    formData.append('Body', body);
    console.log(formData);
    return this.http.post('http://localhost:20377/api/posts', formData,
        {headers: new Headers({'Content-Type': 'multipart/form-data'})})
        .map(res => {
            console.log(res);
        });

Web API core controller:

[EnableCors("CorsPolicy")]
[HttpPost]
public IActionResult CreatePost([FromBody] PostCreate model)
{
    return Ok(model.Body);
}

Answer №1

Issue Resolved

I realized my oversight in forgetting to include headers in the Angular request when passing FormBody data in the Controller Action. Here is the necessary correction:

    [HttpPost]
    public IActionResult CreatePost([FromForm] PostCreate model)
    {
        return Ok(model);
    }

Regarding the Angular code:

    return this.http.post('http://localhost:20377/api/posts', formData)
        .map(res => {
            console.log(res);
</ocde></pre>
</div></answer1>
<exanswer1><div class="answer" i="44299361" l="3.0" c="1496285148" v="1" a="0JDRgNGC0YPRgCDQnNCw0YDQutC+0LI=" ai="8094326">
<p>Solved</p>

<p>The issue was due to not including headers in the Controller Action while passing FormBody data, and also missing them in the Angular request.
The correct approach is as follows:</p>

<pre><code>    [HttpPost]
    public IActionResult CreatePost([FromForm] PostCreate model)
    {
        return Ok(model);
    }

Additionally, in the Angular code:

    return this.http.post('http://localhost:20377/api/posts', formData)
        .map(res => {
            console.log(res);

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

Improving the visualization of large GPS tracks on Google Earth Plugin

I need to display GPS routes on Google Earth using the Google Earth API. However, with approximately 20,000 points per route, the performance is not optimal. The code I have implemented successfully draws the tracks but struggles with rendering time and tr ...

Ensuring the child div's height does not overflow beyond the parent div

When dealing with a parent div and a child div, both having different heights, how can I specifically retrieve the height of the portion of the child div that is within the boundaries of the parent div? Using document.getElementById("id").style.height prov ...

Update all project files in Firebase authentication

A client-side project is being developed using firebase and vue. After a successful login by the user, the authService object gets updated in the Login component, but not in the router. The authService is utilized in both the Login component and AdminNavba ...

Angular Reacts to Pre-Flight Inquiry

I'm facing an issue with my interceptor that manages requests on my controllers. The back-end web API has a refresh token implementation, but when I try to refresh my token and proceed with the request, I encounter the error message "Response to prefl ...

Sorting through mongoose information on the front end using EJS depending on a dropdown pick

Beginner embarking on my inaugural project here. I have developed 2 Mongoose schematics and models for managing categories and products. The products are nested within the corresponding categories model. Using Node and Express, I successfully sent all ca ...

A guide on converting hierarchical database data into JSON format

I have some data stored in a database that represents a hierarchical tree structure. The code snippet below shows how this can be structured using a simple DataTable in C#. using System.Data; namespace DemoConsoleApp { class Program { sta ...

Identify Pressed Shift Key Direction - Leveraging JQuery

I am currently working on a web application that requires users to enter capital letters. However, I want to restrict them from using the right shift key for certain keys like a, s, d, f and the left shift key for h, j, k, l in order to detect whether they ...

Troubleshooting: AngularJS Http Post Method Failing to Execute

I am attempting to make an HTTP POST request to update my database using AngularJS. Although my code is not displaying any errors, the database is not being updated and I'm having trouble pinpointing the issue. Below is the code snippet: //topic-serv ...

Angular mistakenly uses the incorrect router-outlet

Encountering an issue with Angular routing. The main app has its own routing module, and there is a sub module with its own routing module and router-outlet. However, the routes defined in the submodule are being displayed using the root router outlet inst ...

Dynamically switch between showing more and showing less content on each div

Whenever the specific show more button is clicked, the content should be displayed without causing the entire component to re-render. I have tried using a useState, but each time the button is clicked, the whole component re-renders, resulting in long load ...

Exploring the implementation of --history-api-fallback in webpack

let path = require('path') module.exports = { entry:path.resolve('public/src/index.js'), output: { path:__dirname + "/public", filename: "bundle.js" }, module: { loaders: [{ exclude: / ...

Modifying form data when submitting a form

Is there a common or widely-used method for modifying or adding form values before they are serialized and sent to the server upon form submission? I'm looking for a way to change or add these values without having to recreate them. I've come ac ...

AJAX using PHP returns an object containing null values

As a beginner in ajax programming, I encountered a small issue. I created a function in jQuery that makes an ajax call to a PHP file, which then retrieves information about a player from the database. However, when the PHP file responds to the ajax functio ...

Is there a variance in outcomes between constructing a pattern with a string and constructing a pattern with a regular expression "literal" in JavaScript?

Are there any distinctions between using RegExp literals versus strings? http://jsfiddle.net/yMMrk/ String.prototype.lastIndexOf = function(pattern) { pattern = pattern + "(?![\s\S]*" + pattern + ")"; var match = this.match(pattern); ...

Create unique identifiers for the TD elements of Viz.js that will be displayed within the SVG elements

Below is the DOT code snippet in Viz.js that I am working with: digraph G { node [fontname = "font-awesome"]; 17 [id=17, shape="hexagon", label=<<TABLE BORDER="0"> <TR><TD>undefined</TD></TR> <TR><TD>[47-56]< ...

Ways to extract individual values from a Json Array and utilize them individually

I have a JSON data structure that I need to parse and separate each field into different arrays, so that I can use them individually. For instance, I want to split my data into two rooms: room 1 and room 2. After separating the data, I need to format it a ...

Created JSON object providing the number as a string value

I am currently facing an issue with a Vue method where it generates a JSON object from user input values before making an axios put request. The problem I'm encountering is that the JSON object generated converts numbers into strings, causing issues w ...

Mastering the art of using regular expressions (regex) in AngularJS' $httpBackend Expect

When passing a URL as a parameter in a $resource GET request, Angular automatically encodes the parameter. This can make matching the request in the $httpBackend.expectGET method difficult. I've tried using regular expressions to match the expected r ...

What is the best way to apply a hover effect to a specific element?

Within my CSS stylesheet, I've defined the following: li.sort:hover {color: #F00;} All of my list items with the 'sort' class work as intended when the Document Object Model (DOM) is rendered. However, if I dynamically create a brand new ...

Sending a post request in AngularJS using the $resource API

As a beginner in angularjs, I am working on creating a login form that connects to a REST API URL when the user submits the form. http://XXX/XXX/index.php/report/login/format/json Using PostMan REST client to configure the URL works fine! However, when ...