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

What mechanism enables the scores on this sports ticker to refresh automatically without relying on ajax calls?

While browsing scores on , I found myself intrigued by the way they update their scores without using ajax calls or iframes. It's a mystery to me how this functionality is achieved. Can anyone shed some light on how it works? ...

Using Geolocation in HTML5 and JavaScript

Currently, I am working on my debut mobile web application and have successfully integrated Google Maps into it using Geolocation JavaScript API version 3. Now, I am looking to add a button that, when clicked by the user, centers the map on my location o ...

PHP AJAX Request Failing to Transfer Files

I am having trouble with sending files in a PHP AJAX Request: Here is the form code: <form class="frmContact" action="#" method="post"> <div class="col-md-6"> <input type="hidden" name="emailTo" id= ...

Transmitting a plethora of information using jQuery

Here's the code I currently have for sending data: var test={imagename:"apple.jpg",x:"13",y:"33"}; $.ajax({ type: "POST", url: "some.php", data: test, success: function(response){ console.log(response); } }); ...

JavaScript and jQuery validation issues persisting

Here is the HTML code I am using: <script src="js/validate.js"></script> <label>FIRST NAME:</label> <td> <input type="text" class="firstname" id="firstname" onKeyUp="firstname()" /> </td> <td> <label id=" ...

Issues with Skrollr JS on mobile device causing scrolling problem

Currently facing an issue with Skrollr js. It is functioning perfectly in web browsers and mobile devices. However, there seems to be a problem when tapping on a menu or scrolling down arrow as it does not initiate scrolling. Assistance would be greatly ...

What is the necessity of explicitly requesting certain core modules in Node.js?

The documentation explains that certain core modules are included in the Node.js platform itself and are specified within the source code. The terminology can get a bit confusing when it comes to details. The term "global objects" (or standard built-in obj ...

Integrate PHP code within a JSON file

I am working on adding PHP code into a table (data), but I am not sure how to go about it. Can someone help me with this? This is my current code : $data['produit'] = ' <label for="designation" class="col-sm-1 control-l ...

Extracting text from an HTML file and passing it to an Express.js server: A beginner

Currently, I'm attempting to retrieve the values from an HTML text field and store them in variables. I require HTML to capture these values and return the response within the .html file. HTML: <body> <form> ...

Is it possible to replicate the dynamic depth effect of the cards on music.google.com using Angular Material?

Upon hovering over the "day of week music station cards," I observed that they gain depth or height. Can the same effect be achieved with Angular Material Design for cards? Please provide a demo code as an example. ...

Converting JSON data to a different format using SwiftJSON

I am currently facing an issue with obtaining JSON data from web services using Alamofire + SwiftJSON as I am unable to convert the type JSON to another type. Here is an excerpt of my code: var product:JSON = [] override func viewDidLoad() { Alamof ...

Having trouble retrieving the JSON value as it returns undefined

Having trouble extracting specific values from JSON data. I'm trying to retrieve the value of result.datafeed[0].prod[0].vertical[0].deviceProductJson[0].product_brand, but it keeps returning as undefined. To investigate further, I examined the stru ...

Add the element of surprise. The element must be either a Model, an Association, or an object

Struggling with configuring PostgreSQL with Node.js, I followed this tutorial and encountered an error without any specific details: Here is the stacktrace Unhandled rejection Error: Include unexpected. Element has to be either a Model, an Association or ...

The error message displayed reads as follows: "topojson has encountered a TypeError: Unable to access the property 'feature' as

Context A problem has arisen with JavaScript when trying to use the topojson.feature(topology, object) function. It seems that this issue appeared after moving from TopoJSON version 1.6.26 to version 2.x, although the functionality remains similar. The p ...

saving user information with asynchronous HTTP calls

I am encountering an issue while trying to save my form data using AJAX. When I submit the form data in a JavaScript file that calls another PHP file to perform an insertion operation, an error occurs. Here is the code snippet: <button id="submit" cl ...

Definition of Angular 2 File

I have developed a custom Gantt chart library using D3 in vanilla JavaScript. Now, I am trying to integrate it into my Angular 2 application. After installing D3 via npm and adding the necessary type files and the Gantt chart module to node_modules, I enco ...

Having trouble accessing a React component class from a different component class

I just started learning reactjs and javascript. For a simple project, I'm working on creating a login and registration form. The issue I'm facing is that when a user enters their email and password and clicks 'register', instead of movi ...

The AJAX request encountered an unexpected failure that cannot be identified (Using jQuery)

Are you facing issues with a service that returns JSON data? Check out this URL: If you're attempting a simple AJAX request, here's some sample code to get you started: $.ajax({ type: "get", url: "http://api.drag2droid.shamanland.com/ca ...

Transferring information from AJAX to PHP script with the click of a button

Simply put, I am in the process of adding a pop-up update panel to my to-do website using an HTML button. The website already has a login-register system and uses MySQL queries to display different tables for each user. The update buttons on the website c ...

Looking to adjust the fill pattern dynamically

I previously implemented this code: Is there a way to modify the fill image on my 3 buttons to display in 3 distinct colors instead? ...